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

How to create custom image for UIButton using code?

我想使用自定义代码为 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. 使用您的绘图代码绘制到使用 UIGraphicsBeginImageContextWithOptions 打开的图像图形上下文中。

  2. 使用UIGraphicsGetImageFromCurrentImageContext拉出图像。

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

  4. 使用按钮中的图像。

简单示例:

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