【问题标题】:Put image in a rounded CGRect将图像放在圆形 CGRect 中
【发布时间】:2020-05-28 13:03:42
【问题描述】:

我需要在圆角 CGRect 中放置背景图像。

我可以使用下面的代码使 CGRect 的角圆角。

let cornerRadius = CGSize(width: 4.0, height: 4.0)
let bezierPath = UIBezierPath(roundedRect: barRect, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadii: cornerRadius)
context.addPath(bezierPath.cgPath)
context.fillPath()

我可以像下面这样在 CGRect 中绘制图像。

context.draw(image, in: barRect)

但是,我不能绕过路径的拐角,因为我必须使用fillPath(),它会使背景变成纯色。

【问题讨论】:

  • 所有圆角或小于 4?
  • 只是 topLeft 和 topRight
  • 你为什么使用fillPath()close()不填充背景就不能做你需要的吗?
  • 我也试过closePath(),但没有成功。我想问题是我使用不圆角的矩形来绘制图像,但是。我找不到其他方法。
  • @sbekir - 您是否尝试生成具有透明圆顶角的新UIImage?或者您想在 UIImageView 中显示带有圆角顶角的图像?

标签: ios swift cgcontext cgpath


【解决方案1】:

试试这个扩展:

extension UIImage {

    public func imageWithRounded(corners theCorners: UIRectCorner, radius: CGFloat) -> UIImage {
        let cornerRadius = CGSize(width: radius, height: radius)
        let rect = CGRect(origin: .zero, size: size)
        let renderer = UIGraphicsImageRenderer(size: size)
        let img = renderer.image { ctx in
            UIBezierPath(roundedRect: rect, byRoundingCorners: theCorners, cornerRadii: cornerRadius).addClip()
            draw(in: rect)
        }
        return img
    }

}

并像这样使用它:

guard let img = UIImage(named: "myImage") else { return }
let roundedImage = img.imageWithRounded(corners: [.topLeft, .topRight], radius: 20.0)

【讨论】:

    猜你喜欢
    • 2019-01-23
    • 2020-01-01
    • 2017-04-28
    • 1970-01-01
    • 2020-05-04
    • 2022-01-19
    • 2020-12-10
    • 1970-01-01
    • 2017-10-08
    相关资源
    最近更新 更多