MiguelSlv
MiguelSlv

Reputation: 15123

Custom drawing of UIButton

How to programmatically draw an image for a UIButton, instead of passing it as a static resource?

Subclassing UIButton and overriding drawRect method causes the button to loose Tint behavior and possible other drawing effects too. Calling super.drawRect does not restore those behaviors.

Upvotes: 0

Views: 1778

Answers (1)

MiguelSlv
MiguelSlv

Reputation: 15123

I found an solution of my own. Drawing it into an UIImage and pass it to the button as a background image for normal state allows to dynamically create an image and preserves the UIButton effects.

 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
    }
}

Upvotes: 1

Related Questions