【发布时间】:2018-05-01 11:06:40
【问题描述】:
【问题讨论】:
-
关于 SO 的大量答案。请查看stackoverflow.com/questions/4414221/…
标签: ios swift image-editing
【问题讨论】:
标签: ios swift image-editing
确保导入 QuarzCore。
func maskRoundedImage(image: UIImage, radius: CGFloat) -> UIImage {
let imgView: UIImageView = UIImageView(image: image)
let layer = imgView.layer
layer.masksToBounds = true
layer.cornerRadius = radius
UIGraphicsBeginImageContext(imgView.bounds.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundedImage!
}
【讨论】:
每个视图都有一个基础层,您可以在该层上应用圆角半径。然后,您必须在该层上应用 clipToBounds 才能将该遮罩应用到上层 UIView。角半径必须是视图宽度的一半才能获得圆形效果。否则视图的角将被圆角。
例如:
let square = UIView()
square.center = view.center
square.bounds.size = CGSize(width: 100, height: 100)
square.backgroundColor = .red
view.addSubview(square)
square.layer.cornerRadius = 50
square.clipsToBounds = true
【讨论】:
上面提到的方法很好,但是你不能像上图那样得到精确的输出例如你不能得到 alpha 效果。
我建议使用简单的方法。
1) 将新图像添加到带有 Opocity 和圆形的透明背景的项目中。
2) 将上面的新 imageView 添加到主视图,如下所示。
let image = UIImageView(frame: view.bounds)
mage.image = UIImage.init(named:"imageName")
view.addSubview(image)
那么输出应该符合你的要求。
【讨论】: