颜色叠加UIButton图片

3

当我试图在UIButtonImage上叠加颜色时,出现了问题。

覆盖颜色出现在Image下面。

这是我在我的drawRect方法中拥有的代码(我已经子类化了UIButton):

(void)drawRect:(CGRect)rect
{
    CGRect bounds = self.imageView.bounds;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
    CGContextTranslateCTM(context, 0.0, self.imageView.image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextClipToMask(context, bounds, [self.imageView.image CGImage]);
    CGContextFillRect(context, bounds);
}

有什么建议可以让红色位于Image的顶部吗?


你的UIButton是否设置为自定义按钮而不是圆角矩形?如果使用自定义按钮,你应该走在正确的轨道上 :-) - jwknz
@JeffKranenburg 这个按钮是这样初始化的: paletteButton = [PaletteButton buttonWithType:UIButtonTypeCustom]; [paletteButton setImage:[UIImage imageNamed:@"98-palette.png"] forState:UIControlStateNormal]; paletteButton.frame = CGRectMake(110, 13, 24, 20); - Matthew Wilson
顺便问一下,为什么不调用[super drawRect:]呢? - user529758
@H2CO3 不知道我需要这样做,但是我查看了苹果的文档: "If you subclass UIView directly, your implementation of this method (drawRect) does not need to call super. However, if you are subclassing a different view class, you should call [super drawRect:rect] at some point in your implementation." 谢谢你指出这一点。 - Matthew Wilson
1个回答

2

用这个hacky代码成功了:

- (void)drawRect:(CGRect)rect
{
    UIImage* img = [self imageForState:UIControlStateNormal];
    [self setImage:nil forState:UIControlStateNormal];
    CGRect bounds = self.imageView.bounds;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2].CGColor);
    CGContextDrawImage(context, bounds, img.CGImage);
    CGContextFillRect(context, bounds);
}

似乎图像是在 drawRect 之后绘制的,所以除非你将其设置为 nil,否则它会覆盖你在那里绘制的任何内容。

这个解决方案并不是最终的。我会根据接下来的情况进行编辑。

编辑:正确的解决方案是在图像上方添加一个半透明的 UIView,就像这样:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIView* tintView = [[UIView alloc] initWithFrame:self.bounds];
        tintView.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2];
        tintView.userInteractionEnabled = NO;
        [self addSubview:tintView];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        UIView* tintView = [[UIView alloc] initWithFrame:self.bounds];
        tintView.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.2];
        tintView.userInteractionEnabled = NO;
        [self addSubview:tintView];
    }
    return self;
}

注意:您应该在您的 UIButton 子类中完成这个操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接