问题描述
我希望绘制一个UILabel(最好是通过子类化)作为透明标签,但要有坚实的背景。我画了一个简单的示例(对不起,它很丑陋,但要点很清楚:)。)
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 the points across :)).
基本上我有一个UILabel,我希望背景是固定的颜色,并且文本应该是透明的。我不想使用视图背景为文本着色,而是使文本具有100%的透明度,因为我在背景中有一个纹理,我想确保标签内外的线条对齐。
Basically I have a UILabel and I would like the background to be a set colour, and the text should be transparent. I do not want to colour the text with the views background, but instead have it be 100% transparent, since I have a texture in the background that I want to make sure lines up inside and outside of the label.
我一直在过夜浏览SO并在Google上进行搜索,但是我没有找到有用的消息来源。我对CG绘图没有太多的经验,所以我将不胜感激任何链接,帮助,教程或示例代码(也许Apple需要一些我看一下?)。
I've been spending the night browsing SO and searching on Google, but I have found no helpful sources. I don't have much experience with CG drawing, so I would appreciate any links, help, tutorial or sample code (maybe Apple has some I need to have a look at?).
感谢一堆!
推荐答案
我几乎使用任何代码将其重写为UILabel子类,并将其发布在
I've rewritten it as a UILabel subclass using barely any code and posted it on GitHub
要点是您重写drawRect但调用 [super drawRect:rect]
以使UILabel正常渲染。使用白色标签颜色可以使您轻松地将标签本身用作遮罩。
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);
}
这篇关于drawRect绘制“透明”文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!