我想使用自定义代码为UIButton绘制图像。我该怎么做呢?我有可以进入drawRect的代码,但那是UIView,而不是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 :(得分:3)
使用绘图代码绘制到使用UIGraphicsBeginImageContextWithOptions
打开的图像图形上下文。
使用UIGraphicsGetImageFromCurrentImageContext
拉出图像。
使用UIGraphicsEndImageContext
关闭图像图形上下文。
使用按钮中的图像。
简单示例:
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 ...