How can I set UIButton image, which Image is round shape with border I write related code but image not displaying in proper round shape.. Here is my code..
set clipsToBounds = true
for your imageview
btnMyProfile.imageView.clipsToBounds = true
or use
btnMyProfile.imageView.layer.masksToBounds = true
From the apple 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.
else another option use UIBezierPath
This answer is too late but maybe it helps someone
Simply go to storyboard, select your Image View, select Attributes Inspector then change Content Mode from Aspect Fit to Aspect Fill
You should add image to button's background and make sure the size of button is proportional like 20*20, 30*30 etc, and set same corner radius as you already set.
func roundedImageView(imgView: UIImageView, borderWidth: Float, borderColor: UIColor)
{
imgView.layer.cornerRadius = imgView.frame.size.width / 2
imgView.clipsToBounds = true
imgView.layer.borderWidth = CGFloat(borderWidth)
imgView.layer.borderColor = borderColor.cgColor
}
I achieved my desired output the help of @Anbu & also based on the answer of @A.Jam.. Here is my correct code..
let img = UIImageView(image: #imageLiteral(resourceName: "defaultPhoto"))
img.image = img.image?.resizeImageWith(newSize: CGSize(width: 25, height: 25))
btnMyProfile.setImage(img.image, for: .normal)
btnMyProfile.imageView?.contentMode = .scaleAspectFit
//btnMyProfile.imageView?.setRadius()
btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)! / 2
btnMyProfile.imageView?.layer.borderColor = customeMainBlueColor.cgColor
btnMyProfile.imageView?.layer.borderWidth = 2.0
btnMyProfile.imageView?.layer.masksToBounds = true
//someFile.swift
extension UIImage{
//https://stackoverflow.com/questions/42545955/scale-image-to-smaller-size-in-swift3
func resizeImageWith(newSize: CGSize) -> UIImage {
let horizontalRatio = newSize.width / size.width
let verticalRatio = newSize.height / size.height
let ratio = max(horizontalRatio, verticalRatio)
let newSize = CGSize(width: size.width * ratio, height: size.height * ratio)
UIGraphicsBeginImageContextWithOptions(newSize, true, 0)
draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
if you want second type of output you should decrease the size of image.( eg 32x32 or 40x40) and instead of doing
btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)! / 2
you should do
btnMyProfile.imageView?.layer.cornerRadius = image.size.width / 2
the rest of your code seems OK..