【问题标题】:How to create custom image for UIButton using code?如何使用代码为 UIButton 创建自定义图像?
【发布时间】: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


【解决方案1】:
  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 ...

【讨论】:

  • 问题 - 我应该为按钮图像使用什么边界大小?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
相关资源
最近更新 更多