如何设置UIButton的形象,这形象是与边界
圆形我如何设置的UIButton的形象,这形象是有边界圆形我写相关的代码,但图像中适当的圆形不显示.. 这里是我的代码..如何设置UIButton的形象,这形象是与边界
btnMyProfile.setImage(UIImage(named: "MyDefaultImg.png"), for: .normal)
btnMyProfile.imageView?.contentMode = .scaleAspectFit
btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)!/2
btnMyProfile.imageView?.layer.borderColor = UIColor.blue.cgColor
btnMyProfile.imageView?.layer.borderWidth = 2.0
我能为实现我做我期望的输出?请帮我..谢谢..先进
设置clipsToBounds = true
为您的ImageView
btnMyProfile.imageView.clipsToBounds = true
或使用
btnMyProfile.imageView.layer.masksToBounds = true
默认情况下,角落半径并不适用于 层的内容属性的图像;它仅适用于背景颜色和层的 边界。然而,masksToBounds属性设置为 真正导致被夹在圆角的内容。
别的另一种选择使用UIBezierPath
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
}
但是我需要大尺寸的按钮(矩形形状)这就是为什么给圆形形状图像视图 – NiravS
检查更新码 –
你可以设置你的形象的高度和宽度相同。
像
20X20,30X30 ..
如果你想第二类型的输出,你应该减少图像的大小(32×32如40×或),并与其做btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)!/2
你应该做的
btnMyProfile.imageView?.layer.cornerRadius = image.size.width/2
你的代码的其余部分似乎OK ..
我实现d我的期望输出@Anbu &的帮助也是基于@ A.Jam .. 这里的答案是本人正确的代码..
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!
}
}
您应该添加图片按钮的背景,并确保的大小按钮的比例像20 * 20,30 * 30等,并设置相同的角半径,因为您已经设置。
我改变了但没有效果。 – NiravS
@NiravS - 检查更新后的答案 –
我将按钮大小更改为Square,因此可以看到完美的圆形,但我需要在按钮中设置小图像。那我该怎么办? – NiravS