2016-01-31 49 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

相关问题