2011-10-25 61 views
5

調用UIButton的繪圖順序是什麼?在UIButton的背景圖片上自定義繪圖

我有一個UIButton子類,我們稱之爲UIMyButton。我將它添加到一個.xib控制器並給它一個背景圖像。然後在UIMyButton.m文件中,我重寫了drawRect方法並繪製了一個形狀。 喜歡的東西:

- (void)drawRect:(CGRect)rect { 
    CGContextRef c = UIGraphicsGetCurrentContext(); 
    CGContextSetFillColorWithColor(c, [UIColor orangeColor].CGColor); 
    CGContextFillRect(c, rect); 
} 

的問題是,它繪製背景圖片下方的橙色矩形。什麼方法負責繪製/更新背景圖像(例如更新「點擊」)?如何在不添加額外的自定義子視圖的情況下在頂部強制繪製(或者是子視圖本身的背景圖像)?

我只是想清楚瞭解UIButton繪圖順序的工作原理。

+0

嗨巴斯泰克 - 你在嗎?真的,你應該打勾下面的優秀答案! – Fattie

回答

4

解決方案是不使用按鈕的背景。相反,在drawRect方法內繪製圖像,如下所示:

-(void)drawRect:(CGRect)rect 
{ 
    CGContextRef ctx=UIGraphicsGetCurrentContext(); 

    UIImage *image = [UIImage imageNamed:@"image.jpg"]; 
    [image drawInRect:self.bounds]; 

    CGContextSetFillColorWithColor(c, [UIColor orangeColor].CGColor); 
    CGContextFillRect(c, rect); 
}