我想使用自定義代碼爲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];
馬茨回答是好。但是它也與UIVutton從UIView繼承是非常相關的。所以你可以創建一個新的UIButton子類,重寫drawRect:用你在這裏的東西,把你的按鈕換成你的新子類,並且完全避免使用圖像。換句話說,你在上面寫'但是這是UIView,而不是UIButton'。那麼UIButton是一個UIView :) – Jef