如何使用代码为UIButton创建自定义图像?

时间:2016-01-31 02:09:52

标签: ios objective-c uibutton drawrect

我想使用自定义代码为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];

1 个答案:

答案 0 :(得分:3)

  1. 使用绘图代码绘制到使用UIGraphicsBeginImageContextWithOptions打开的图像图形上下文。

  2. 使用UIGraphicsGetImageFromCurrentImageContext拉出图像。

  3. 使用UIGraphicsEndImageContext关闭图像图形上下文。

  4. 使用按钮中的图像。

  5. 简单示例:

    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 ...