2016-01-31 91 views
0

我想使用自定義代碼爲UIButton繪製圖像。我該如何去做呢?我有可以進入drawRect的代碼,但這是UIView,而不是UIButton。如何使用代碼爲UIButton創建自定義圖像?

在自定義視圖的drawRect:

@implement MyCustomView 

- (void)drawRect:(CGRect)rect { 
    UIColor *color = [UIColor blueColor]; 

    // Vertical stroke 
    { 
     UIBezierPath *bezierPath = [UIBezierPath bezierPath]; 
     [bezierPath moveToPoint: CGPointMake(20, 0)]; 
     [bezierPath addLineToPoint: CGPointMake(20, 40)]; 
     [color setStroke]; 
     bezierPath.lineWidth = 1; 
     [bezierPath stroke]; 
    } 
} 

- (UIImage *)imageFromView { 
     [self drawRect:CGRectMake(0, 0, 40, 40)]; 

     UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0); 
     [self.layer renderInContext:UIGraphicsGetCurrentContext()]; 

     UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); 

     UIGraphicsEndImageContext(); 

     return img; 
    } 

在按鈕代碼:

UIButton *button = [[UIButton alloc] init]; 
MyCustomView *view = [[MyCustomView alloc] init]; 
[button setImage:view.imageFromView forState:UIControlStateNormal]; 
+0

馬茨回答是好。但是它也與UIVutton從UIView繼承是非常相關的。所以你可以創建一個新的UIButton子類,重寫drawRect:用你在這裏的東西,把你的按鈕換成你的新子類,並且完全避免使用圖像。換句話說,你在上面寫'但是這是UIView,而不是UIButton'。那麼UIButton是一個UIView :) – Jef

回答

3

使用繪圖代碼來繪製與UIGraphicsBeginImageContextWithOptions開了一個圖像的圖形上下文。用UIGraphicsGetImageFromCurrentImageContext拉出圖像。用UIGraphicsGetImageFromCurrentImageContext關閉圖像圖形上下文。使用按鈕中的圖像。

簡單的例子:下面

UIGraphicsBeginImageContextWithOptions(CGSizeMake(100,100), NO, 0); 
UIBezierPath* p = 
    [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0,0,100,100)]; 
[[UIColor blueColor] setFill]; 
[p fill]; 
UIImage* im = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
// im is the blue circle image, do something with it here ... 
+0

並看看我的書:http://www.apeth.com/iOSBook/ch15.html#_graphics_contexts – matt

+0

問題 - 我應該使用什麼邊界大小的按鈕圖像? – Boon

相關問題