2012-12-26 143 views
3

我在試圖用顏色覆蓋UIButtonImage時遇到此問題。顏色疊加UIButton圖像

重疊顏色出現在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頂部的紅色任何想法?

+0

你的UIButton設置爲自定義按鈕而不是RoundRect?自定義你應該在正確的軌道上:-) –

+0

@JeffKranenburg按鈕初始化是這樣的: 'paletteButton = [PaletteButton buttonWithType:UIButtonTypeCustom]; [paletteButton setImage:[UIImage imageNamed:@「98-palette.png」] forState:UIControlStateNormal]; paletteButton.frame = CGRectMake(110,13,24,20);' –

+0

順便說一句,爲什麼不調用'[super drawRect:]'? – 2012-12-26 18:46:23

回答

2

成功與此哈克代碼:

- (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繪製。

這是解決方案不是最終的。我將用接下來的內容編輯它。

編輯:正確的解決辦法是在圖片上添加一個半透明的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子類中做到這一點。