【发布时间】:2016-01-31 02:09:51
【问题描述】:
我想使用自定义代码为 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];
【问题讨论】:
-
Matts 下面的回答很好。但是 UIButton 从 UIView 继承也非常相关。所以你可以创建一个新的 UIButton 子类,用你在这里的东西覆盖 drawRect:,将你的按钮换成你的新子类,并完全避免使用图像。换句话说,上面你写的是'但那是针对 UIView,而不是 UIButton'。那么一个 UIButton 就是一个 UIView :)
标签: ios objective-c uibutton drawrect