What I'm essentially trying to do is have a text label 'cut' a text-shaped hole through the view. I've tried using self.mask = uiLabel
but those refused to position the text correctly so I'm approaching this through Core Graphics.
Here's the code that isn't working (in the draw(_ rect: CGRect)
):
let context = (UIGraphicsGetCurrentContext())!
// Set mask background color
context.setFillColor(UIColor.black.cgColor)
context.fill(rect)
context.saveGState()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes = [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium),
NSForegroundColorAttributeName: UIColor.white
]
let string = NSString(string: "LOGIN")
// This wouldn't vertically align so we calculate the string size and create a new rect in which it is vertically aligned
let size = string.size(attributes: attributes)
let position = CGRect(
x: rect.origin.x,
y: rect.origin.y + (rect.size.height - size.height) / 2,
width: rect.size.width,
height: size.height
)
context.translateBy(x: 0, y: rect.size.height)
context.scaleBy(x: 1, y: -1)
string.draw(
in: position,
withAttributes: attributes
)
let mask = (context.makeImage())!
context.restoreGState()
// Redraw with created mask
context.clear(rect)
context.saveGState()
// !!!! Below line is the problem
context.clip(to: rect, mask: mask)
context.restoreGState()
Essentially I've successfully created the code to create a CGImage
(the mask
variable) which is the mask I want to apply to the whole image.
The marked line when replaced with context.draw(mask, in: rect)
(to view the mask) correctly displays. The mask shows (correctly) as:
However once I try to apply this mask (using the context.clip(to: rect, mask: mask)
) nothing happens!. Actual result:
Desired result is:
but for some reason the mask is not being correctly applied.
This code seems like it should work as I've read the docs over and over again. I've additionally tried to create the mask in a separate CGContext which didn't work. Also when I tried to convert the CGImage (mask
) to CGColorSpaceCreateDeviceGray()
using .copy(colorSpace:)
, it returned nil
. I've been at this for two days so any help is appreciated
I'm not actually sure that you will enjoy the code below. It was made by using the PaintCode. Text will be always at the center of rounded rectangle. Hope it will help you.
Code, put it inside draw(_ rect: CGRect):
Results: