用颜色填充UILabel的透明文本

时间:2014-04-05 09:14:15

标签: ios objective-c uilabel

can we change UILabel text colour with different text

我用UILabel子类使用覆盖drawRect方法绘制它,但我想改变颜色,并希望用滑块设置alpha值。

- (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);

    if (self.layer.cornerRadius != 0.0f) {
        CGContextAddPath(context, CGPathCreateWithRoundedRect(rect, self.layer.cornerRadius, self.layer.cornerRadius, nil));
        CGContextClip(context);
    }

    CFRelease(mask);  mask = NULL;
    [maskedBackgroundColor set];
   CGContextFillRect(context, rect);

    CGContextRestoreGState(context);

}

1 个答案:

答案 0 :(得分:1)

创建一些属性:

/** The value for the red channel of the colour of the label. */
@property (nonatomic, strong) CGFloat rValue;
/** The value for the green channel of the colour of the label. */
@property (nonatomic, strong) CGFloat gValue;
/** The value for the blue channel of the colour of the label. */
@property (nonatomic, strong) CGFloat bValue;
/** The value for the alpha channel of the colour of the label. */
@property (nonatomic, strong) CGFloat aValue;

使用各自的UISlider值更新它们。

在每个UISlider回拨电话- (void)setNeedsDisplay中触发drawRect

drawRect执行此操作:

UIColor fillColour = [[UIColor alloc] initWithRed:self.rValue green:self.gValue blue:self.bValue alpha:self.aValue];
[fillColour setFill];

这会将填充颜色设置为滑块确定的颜色。然后当你填充矩形时,它就是那种颜色。