我不认为你将能够直接用 UILabel 做到这一点。我所做的是将它分解成几部分:
如何仅绘制标签的背景。为此,我从字符串中抄袭了 CGPathRef 中的代码,以将字符串转换为路径。然后子类化 UILabel 并添加以下 drawRect 做了适当的事情。
-(void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
// Convert the attributed text to a UIBezierPath
CGPathRef path = [self.attributedText createPath];
// Adjust the path bounds horizontally as requested by the view
CGRect bounds = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
CGAffineTransform xform = CGAffineTransformMakeTranslation(bounds.origin.x, bounds.origin.y);
// Adjust the path bounds vertically because it doesn't seem to be taken into account yet
bounds = CGPathGetBoundingBox(path);
xform = CGAffineTransformTranslate(xform, 0., (self.bounds.size.height - bounds.size.height) / 2.);
// Apply the transform to the path
path = CGPathCreateCopyByTransformingPath(path, &xform);
// Set colors, the fill color should be the background color because we're going
// to draw everything BUT the text, the text will be left clear.
CGContextSetFillColorWithColor(ctx, self.textColor.CGColor);
// Flip and offset things
CGContextScaleCTM(ctx, 1., -1.);
CGContextTranslateCTM(ctx, 0., 0. - self.bounds.size.height);
// Invert the path
CGContextAddRect(ctx, self.bounds);
CGContextAddPath(ctx, path);
CGContextDrawPath(ctx, kCGPathEOFill);
// Discard the path
CFRelease(path);
// Restore gstate
CGContextRestoreGState(ctx);
}
如果您在界面生成器中创建 UILabel,设置类,将背景颜色设置为清除,将前景色设置为您建议的填充颜色,背景将显示在文本所在的位置。
为了模糊通过标签显示的身体,我在标签下方放置了一个 FXBlurView ( https://github.com/nicklockwood/FXBlurView ),并带有尺寸约束以保持它们对齐。
您可以在https://github.com/dwb357/TransparentLabel看到这一切。