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

标签 ios objective-c uibutton drawrect

我想使用自定义代码为 UIButton 绘制图像。我该怎么做呢?我有可以进入 drawRect 的代码,但那是针对 UIView,而不是 UIButton。

在自定义 View 的 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 ...

关于ios - 如何使用代码为 UIButton 创建自定义图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109558/

相关文章:

以png图像为背景的iOS5按钮透明度

ruby-on-rails - RestKit 0.10.1 with Core Data 陡峭的学习曲线

javascript - 我如何在我的网页上为 iphone 用户创建一个有应用程序的注释?

ios - 设置了关闭键盘的代码,但它仍然不起作用?

objective-c - SpriteKit MouseMoved 不工作

ios - ScrollView 中的分段控件

ios - 如何在Unity中使用ARkit2.0加载现实世界中的多个ARworld map ?

iphone - Objective C @property 注释

ios - 将目标添加到 UIButton 不起作用

ios - 如何在 Xamarin(iOS) 中将按钮从右移到左