【发布时间】:2021-01-14 07:19:37
【问题描述】:
我正在尝试将cornerRadius 添加到UIImageView,这是一个小高度(7pt)的矩形。 UIImageView 在右侧被错误地裁剪。
奇怪的是UIImageView 在左侧是完美的圆形,但同时在右侧有一个额外的白色区域。奇怪的是它有时会起作用,右角的圆度取决于UIImageView 宽度。如果我将宽度设置为 30%,那么右角问题就会消失。
我尝试了什么: 只需通过cornerRadius设置角
layer.cornerRadius = frame.size.height / 2
clipsToBounds = true
通过图形上下文设置角
func withRoundedCorners(radius: CGFloat, rect: CGRect) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
通过蒙版和路径设置角
extension UIImageView {
func roundCornersForAspectFit(radius: CGFloat) {
if let image = self.image {
// calculate drawingRect
let boundsScale = bounds.size.width / bounds.size.height
let imageScale = image.size.width / image.size.height
var drawingRect: CGRect = bounds
if boundsScale > imageScale {
drawingRect.size.width = drawingRect.size.height * imageScale
drawingRect.origin.x = (bounds.size.width - drawingRect.size.width) / 2
} else {
drawingRect.size.height = drawingRect.size.width / imageScale
drawingRect.origin.y = (bounds.size.height - drawingRect.size.height) / 2
}
let path = UIBezierPath(roundedRect: drawingRect, cornerRadius: radius)
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
}
玩过不同类型的图片内容模式
.scaleAspectFill
or
.scaleAspectFit
or
.scaleToFill
结果总是一样的。
此外,如果我从UIImageView 中删除图像并将backgroundColor 设置为一些随机颜色来测试它,那么右侧的圆角就可以完美地工作。
会是什么?
【问题讨论】:
-
时机就是一切。 什么时候你这样做?
-
@matt 我在
override func layoutSubviews()内部或之后尝试过 -
好吧,这仍然不是minimal reproducible example。请提供我们重现问题所需的一切(仅此而已)。
-
请附上界面生成器ss
标签: ios objective-c swift uiimageview cornerradius