iOS UIView subclass, draw see-through text to background

后端 未结 4 1829
灰色年华
灰色年华 2020-12-01 08:51

I want to draw text onto my subclass on UIView so that the text is cut out of the shape and the background behind the view shows through, just like in the OSX Mavericks logo

4条回答
  •  没有蜡笔的小新
    2020-12-01 09:18

    I actually figured out how to do it on my own surprisingly but @StatusReport's answer is completely valid and works as it stands now.

    Here's how I did it:

    -(void)drawRect:(CGRect)rect{
        CGContextRef context = UIGraphicsGetCurrentContext();
        [[UIColor darkGrayColor]setFill]; //this becomes the color of the alpha mask
        CGContextFillRect(context, rect);
        CGContextSaveState(context);
        [[UIColor whiteColor]setFill];
        //Have to flip the context since core graphics is done in cartesian coordinates
        CGContextTranslateCTM(context, 0, rect.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        [textToDraw drawInRect:rect withFont:[UIFont fontWithName:@"HelveticaNeue-Thin" size:40];
        CGContextRestoreGState(context);
        CGImageRef alphaMask = CGBitmapContextCreateImage(context);
        [[UIColor whiteColor]setFill];
        CGContextFillRect(context, rect);
        CGContextSaveGState(context);
        CGContentClipToMask(context, rect, alphaMask);
        [backgroundImage drawInRect:rect];
        CGContextRestoreGState(context);
        CGImageRelease(alphaMask);
    }
    
    - (void)setTextToDraw:(NSString*)text{
        if(text != textToDraw){
            textToDraw = text;
            [self setNeedsDisplay];
        }
    }
    

    I have an @synthesize declaration for textToDraw so I could override the setter and call [self setNeedsDisplay]. Not sure if that's totally necessary or not.

    I'm sure this has some typos but I can assure you, the spell checked version runs just fine.

提交回复
热议问题