ios - Core Graphics CGImage mask not affecting -
what i'm trying have text label 'cut' text-shaped hole through view. i've tried using self.mask = uilabel
refused position text correctly i'm approaching through core graphics.
here's code isn't working (in 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") // wouldn't vertically align calculate string size , create new rect in 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 created mask context.clear(rect) context.savegstate() // !!!! below line problem context.clip(to: rect, mask: mask) context.restoregstate()
essentially i've created code create cgimage
(the mask
variable) mask want apply whole image.
the marked line when replaced context.draw(mask, in: rect)
(to view mask) correctly displays. mask shows (correctly) as:
however once try apply mask (using context.clip(to: rect, mask: mask)
) nothing happens!. actual result:
desired result is:
but reason mask not being correctly applied.
this code seems should work i've read docs on , on again. i've additionally tried create mask in separate cgcontext didn't work. when tried convert cgimage (mask
) cgcolorspacecreatedevicegray()
using .copy(colorspace:)
, returned nil
. i've been @ 2 days appreciated
if want label have translucent text, can use blend modes instead of masks.
public class knockoutlabel: uilabel { public override func draw(_ rect: cgrect) { let context = uigraphicsgetcurrentcontext()! context.setblendmode(.clear) self.drawtext(in: rect) } }
make sure set isopaque
false
though; default view assumes opaque, since use opaque background color.
Comments
Post a Comment