Image on a button with drawing a circle

586 views Asked by At

I have button on which I show an image. The Image (image in a circle as png with transparent color outside of the circle) is in a circle and the Button is transparent. When I draw the button on the screen I can see only the circeled button. This works fine so far.

Now I would like to draw a black circle around the Image at runtime. Any hints on how to do that ?

my function creating the button:

  func draw_button(sImage:String,X:CGFloat,Y:CGFloat, iTag:Int){

        // Back Button
        var sImagename=sImage;
        var fButtonx:CGFloat=X;
        var fButtony:CGFloat=Y;

        var thebutton=UIButton(frame: CGRectMake(fButtonx, fButtony, iButtonSize, iButtonSize));
        thebutton.addTarget(self, action: "buttonActionBotton:", forControlEvents: UIControlEvents.TouchUpInside)
        thebutton.tag = iTag;
        var image = UIImage(named: sImagename);


        thebutton.setImage(image, forState: .Normal)
        var transparent:UIColor=UIColor(red: 0, green: 0, blue: 0, alpha: 0.0);
        thebutton.backgroundColor=transparent;
        thebutton.layer.backgroundColor=transparent.CGColor;
        self.view.addSubview(backButton);


    }

Any hints on how I could do that ?

1

There are 1 answers

1
Sergii Martynenko Jr On BEST ANSWER

You can use subview situated just under button. Set its background to black colour and use its layer cornerRadius property to achieve circle shape.

let circleSubview = UIView(frame: CGRectMake(fButtonx, fButtony, iButtonSize, iButtonSize);
circleSubview.backgroundColor = UIColor.blackColor();
circleSubview.layer.cornerRadius = //whatever you need; I believe, it should be something around 10.0 or more - try it yourself


//after backButton added to view hierarchy 
self.view.insertSubview(view: circleSubview, belowSubview : backButton)

Some advices - you don't need your views to be variables. Use let instead var. And you have class function UIColor.clearColor() instead of creating transparent colour by yourself.