【问题标题】:Custom drawing of UIButtonUIButton的自定义绘制
【发布时间】:2015-06-21 20:13:48
【问题描述】:

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

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

【问题讨论】:

    标签: swift uikit drawing controls


    【解决方案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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 2011-08-10
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多