drawRect drawing 'transparent' text?

前端 未结 3 647
北荒
北荒 2020-12-23 18:32

I am looking to draw a UILabel (preferable through subclassing) as a transparent label, but with solid background. I draw up an quick example (sorry, it\'s ugly, but it gets

3条回答
  •  难免孤独
    2020-12-23 18:51

    I've rewritten it as a UILabel subclass using barely any code and posted it on GitHub

    The gist of it is you override drawRect but call [super drawRect:rect] to let the UILabel render as normal. Using a white label color lets you easily use the label itself as a mask.

    - (void)drawRect:(CGRect)rect
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        // let the superclass draw the label normally
        [super drawRect:rect];
    
        CGContextConcatCTM(context, CGAffineTransformMake(1, 0, 0, -1, 0, CGRectGetHeight(rect)));
    
        // create a mask from the normally rendered text
        CGImageRef image = CGBitmapContextCreateImage(context);
        CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBitsPerComponent(image), CGImageGetBitsPerPixel(image), CGImageGetBytesPerRow(image), CGImageGetDataProvider(image), CGImageGetDecode(image), CGImageGetShouldInterpolate(image));
    
        CFRelease(image); image = NULL;
    
        // wipe the slate clean
        CGContextClearRect(context, rect);
    
        CGContextSaveGState(context);
        CGContextClipToMask(context, rect, mask);
    
        CFRelease(mask);  mask = NULL;
    
        [self RS_drawBackgroundInRect:rect];
    
        CGContextRestoreGState(context);
    
    }
    

提交回复
热议问题