swift - UIButton的自定义绘制

标签 swift uikit drawing controls

如何以编程方式为 UIButton 绘制图像,而不是将其作为静态资源传递?

子类化UIButton并重写drawRect方法会导致按钮失去Tint行为以及可能的其他绘图效果。调用 super.drawRect 不会恢复这些行为。

最佳答案

我找到了自己的解决方案。将其绘制到 UIImage 中并将其作为正常状态的背景图像传递给按钮,允许动态创建图像并保留 UIButton 效果。

 class MyButton: UIButton {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)       
        let image = createImage(self.bounds)         
        self.setBackgroundImage(image, forState: UIControlState.Normal)   
    }


    func createImage(rect: CGRect) -> UIImage{

        UIGraphicsBeginImageContext(rect.size)

        let context = UIGraphicsGetCurrentContext();

        //just a circle
        CGContextSetFillColorWithColor(context,  UIColor.whiteColor().CGColor);
        CGContextFillEllipseInRect(context, CGRectInset(rect, 4, 4));
        CGContextStrokePath(context);

        let image =  UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext()

        return image
    }
}

关于swift - UIButton的自定义绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30968885/

相关文章:

ios - 在应用程序自定义键盘 swift ios7/8

ios - ScrollView 不显示图像但滚动?

iphone - 结合UIView动画 block 和OpenGL ES渲染

java - 创建锥形笔划

java - 在 Java 中创建位图的错误

ios - 快速通过编码按钮/功能发送数据

macos - 不寻常的核心数据行为 - 保存一个对象会影响另一个对象吗?

ios - 我需要在 UIScrollView 中的特定点之后滚动 Storyboard 中的 float (固定)UIView

ios - 如何创建更改特定 uicollectionviewcell 属性的操作?

java - JFrame 中的 setColor 不起作用