Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set corner radius of imageView?

In Objective-C such line

self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0f;

does its job, I tried it in Swift using analogy

self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0

and it doesn't change anything, the corners are the same as before. Moreover, Xcode does not show any syntax errors. Does Swift support any other way to reach this goal? I checked some other threads here and usually it's getting done in Swift in the way showed above.

like image 323
theDC Avatar asked Jan 09 '15 13:01

theDC


People also ask

How do I change the radius of a corner in Photoshop?

Click the "Rectangle - Location" layer so that you can activate that layer for editing. Using the Path Selection Tool, click the light blue "Location" square. In the Properties panel, change the corner radius to "17 px" for all corners for this shape.


4 Answers

Layer draws out of clip region, you need to set it to mask to bounds:

self.mainImageView.layer.masksToBounds = true

From the docs:

By default, the corner radius does not apply to the image in the layer’s contents property; it applies only to the background color and border of the layer. However, setting the masksToBounds property to true causes the content to be clipped to the rounded corners

like image 58
DarthMike Avatar answered Oct 18 '22 07:10

DarthMike


There is one tiny difference in Swift 3.0 and Xcode8

Whenever you want to apply corner radius to UIView, make sure you call yourUIView.layoutIfNeeded() before calling cornerRadius.

Otherwise, it will return the default value for UIView's height and width (1000.0) which will probably make your View disappear.

Always make sure that all effects that changes the size of UIView (Interface builder constraints etc) are applied before setting any layer properties.

Example of UIView class implementation

class BadgeView: UIView {

  override func awakeFromNib() {

    self.layoutIfNeeded()
    layer.cornerRadius = self.frame.height / 2.0
    layer.masksToBounds = true

   }
 }
like image 26
theDC Avatar answered Oct 18 '22 06:10

theDC


You can define border radius of any view providing an "User defined Runtime Attributes", providing key path "layer.cornerRadius" of type string and then the value of radius you need ;) See attached images below:

Configuring in XCode

Result in emulator

like image 24
Marcelo Tadeu Avatar answered Oct 18 '22 07:10

Marcelo Tadeu


try this

self.mainImageView.layer.cornerRadius = CGRectGetWidth(self.mainImageView.frame)/4.0
self.mainImageView.clipsToBounds = true
like image 19
Anbu.Karthik Avatar answered Oct 18 '22 05:10

Anbu.Karthik