UIButton的自定义绘图

时间:2015-06-21 20:13:49

标签: swift uikit drawing controls

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

UIButton进行子类化并覆盖drawRect方法会导致按钮松散Tint行为以及可能的其他绘制效果。调用super.drawRect不会恢复这些行为。

1 个答案:

答案 0 :(得分:1)

我找到了自己的解决方案。将其绘制到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
    }
}