Created
September 3, 2020 14:06
-
-
Save h4yder/f341acaad58044ac962a297a2d15500e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private func generateTextMask() -> CGImage? { | |
guard frame.size.width != 0.0, | |
frame.size.height != 0.0, | |
let attributedString = maskAttributedText() else { | |
return nil | |
} | |
let bitmap = Bitmap(width: frame.size.width, height: frame.size.height) | |
bitmap.context.clear(bitmap.bounds) | |
let framesetter = CTFramesetterCreateWithAttributedString(attributedString) | |
let range = CFRange(location: 0, length: attributedString.length) | |
var effectiveRange: CFRange = .init(location: 0, length: 0) | |
let suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, range, nil, bitmap.bounds.size, &effectiveRange) | |
if effectiveRange.length < range.length { | |
print("VideoLabel ERROR: The view's frame is too small to display the full text.") | |
} | |
let path = CGMutablePath() | |
let bitmapBounds = bitmap.bounds | |
let textRect: CGRect | |
let alignment = textAlignment(for: attributedString) | |
switch alignment { | |
case .left, .natural: | |
textRect = CGRect(x: 0.0, | |
y: (bitmapBounds.size.height - suggestedSize.height) * 0.5, | |
width: suggestedSize.width, | |
height: suggestedSize.height) | |
case .right: | |
textRect = CGRect(x: bitmapBounds.size.width - suggestedSize.width, | |
y: (bitmapBounds.size.height - suggestedSize.height) * 0.5, | |
width: suggestedSize.width, | |
height: suggestedSize.height) | |
case .justified, .center: | |
textRect = CGRect(x: (bitmapBounds.size.width - suggestedSize.width) * 0.5, | |
y: (bitmapBounds.size.height - suggestedSize.height) * 0.5, | |
width: suggestedSize.width, | |
height: suggestedSize.height) | |
@unknown default: | |
textRect = CGRect(x: (bitmapBounds.size.width - suggestedSize.width) * 0.5, | |
y: (bitmapBounds.size.height - suggestedSize.height) * 0.5, | |
width: suggestedSize.width, | |
height: suggestedSize.height) | |
} | |
path.addRect(textRect) | |
let textRectInViewSpace = CGRect(x: textRect.origin.x / Bitmap.contentScale, | |
y: textRect.origin.y / Bitmap.contentScale, | |
width: textRect.size.width / Bitmap.contentScale, | |
height: textRect.size.height / Bitmap.contentScale) | |
let textRectInScreenSpace = UIAccessibility.convertToScreenCoordinates(textRectInViewSpace, in: self) | |
accessibilityFrame = textRectInScreenSpace | |
let ctFrame = CTFramesetterCreateFrame(framesetter, CFRange(location: 0, length: CFIndex(attributedString.length)), path, nil) | |
CTFrameDraw(ctFrame, bitmap.context) | |
return bitmap.cgImage | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment