我用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);
}
答案 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];
这会将填充颜色设置为滑块确定的颜色。然后当你填充矩形时,它就是那种颜色。