圆形 UIView 中的 UIImage swift
UIImage in a Rounded UIView swift
我创建了一个 UIView,并在 UIView 中添加了一个 Imageview。我给了 UIView 角半径并且它有效,我现在的问题是我放置在里面的图像不尊重视图的角半径,因此,它将整个图像显示为矩形而不是左上角和右上角弯曲到与 UIView 相同的半径。我的代码如下所示。
let bgView: UIView = {
let bgView = UIView()
bgView.backgroundColor = .white
return bgView
}()
let propertyImage: DefaultImageView = {
let img = DefaultImageView(frame: .zero)
img.clipsToBounds = true
img.layer.masksToBounds = true
img.image = #imageLiteral(resourceName: "icons8-name-filled-30")
img.contentMode = .scaleToFill
return img
}()
这给出了圆形卡片视图
extension UIView {
func addShadowAndRoundCorners() {
layer.shadowOpacity = 1
layer.shadowOffset = CGSize.zero
layer.shadowColor = UIColor.darkGray.cgColor
layer.cornerRadius = 12
}
}
所以我添加了圆形样式 bgView.addShadowAndRoundCorners
如何使图像视图保持在 UIView 的圆角范围内
yes 的 clipsToBounds 也需要添加到容器视图中,以强制子视图不在外部呈现:
bgView.clipsToBounds = true
或者您可以直接将 imageView 本身四舍五入。
如果您只希望 UIImageView 的左上角和右上角变圆,您可能必须在显示图像之前使用遮罩。
创建一个与图片大小相同的CGContext,在CGContext中创建mask,然后将图片绘制到context中,mask会被应用,然后从context中获取新的图片并放入.image中的 UIImageView。
我创建了一个 UIView,并在 UIView 中添加了一个 Imageview。我给了 UIView 角半径并且它有效,我现在的问题是我放置在里面的图像不尊重视图的角半径,因此,它将整个图像显示为矩形而不是左上角和右上角弯曲到与 UIView 相同的半径。我的代码如下所示。
let bgView: UIView = {
let bgView = UIView()
bgView.backgroundColor = .white
return bgView
}()
let propertyImage: DefaultImageView = {
let img = DefaultImageView(frame: .zero)
img.clipsToBounds = true
img.layer.masksToBounds = true
img.image = #imageLiteral(resourceName: "icons8-name-filled-30")
img.contentMode = .scaleToFill
return img
}()
这给出了圆形卡片视图
extension UIView {
func addShadowAndRoundCorners() {
layer.shadowOpacity = 1
layer.shadowOffset = CGSize.zero
layer.shadowColor = UIColor.darkGray.cgColor
layer.cornerRadius = 12
}
}
所以我添加了圆形样式 bgView.addShadowAndRoundCorners
如何使图像视图保持在 UIView 的圆角范围内
yes 的 clipsToBounds 也需要添加到容器视图中,以强制子视图不在外部呈现:
bgView.clipsToBounds = true
或者您可以直接将 imageView 本身四舍五入。
如果您只希望 UIImageView 的左上角和右上角变圆,您可能必须在显示图像之前使用遮罩。
创建一个与图片大小相同的CGContext,在CGContext中创建mask,然后将图片绘制到context中,mask会被应用,然后从context中获取新的图片并放入.image中的 UIImageView。