【问题标题】:Add UIImage in a UIGraphicsImageRenderer在 UIGraphicsImageRenderer 中添加 UIImage
【发布时间】:2018-08-05 00:56:51
【问题描述】:

我是 Swift 的初学者,我想使用 UIGraphicsImageRenderer 将图像添加到自定义路径绘制中。我给你看我的代码:

let size = CGSize(width:newWidth , height:height)
let f = UIGraphicsImageRendererFormat.default()
f.opaque = false
let r = UIGraphicsImageRenderer(size:size, format: f)
let im = r.image { _ in
    let leftUpPath = UIBezierPath()
    leftUpPath.move(to: CGPoint(x: 0, y: 0))
    leftUpPath.addArc(withCenter: CGPoint(x: cornerRadiusView, y: cornerRadiusView),
                      radius: cornerRadiusView,
                      startAngle: .pi * 3 / 2,
                      endAngle: .pi,
                      clockwise: false)
    leftUpPath.addLine(to: CGPoint(x: 0, y: height))
    leftUpPath.addLine(to: CGPoint(x: newWidth - cutPicture, y: height))
    leftUpPath.addLine(to: CGPoint(x: newWidth, y: 0))
    leftUpPath.addLine(to: CGPoint(x: cutPicture, y: 0))
    UIColor(rgb : 0xffffff).setFill()
    leftUpPath.fill()
}
let iv = UIImageView(image:im)
iv.frame.origin = CGPoint(x: 0, y: 0)
iv.clipsToBounds = true

let userPicture = UIImageView(image: picture)
userPicture.frame = iv.bounds
userPicture.clipsToBounds = true

iv.addSubview(userPicture)
cardView.addSubview(iv)

我的自定义路径运行良好,但是当我添加 userPicture 时,图像不会超出路径的范围......

这就是我所拥有的:

这就是我想要的:

(用猫图片替换白色背景):

我做错了什么?

【问题讨论】:

  • 想添加您当前的结果以及预期结果吗? :)
  • Clip to bounds only 意味着UIImageView 将防止图像“过度填充”视图的边界
  • @Glenn 完成!把白色的bg换成猫图就是我想要的!

标签: ios swift uiimageview uibezierpath


【解决方案1】:

我用另一个解决方案解决了我的问题(将路径添加到 shapeLayer 并将其添加到 UIImageView 的掩码):

    let path = UIBezierPath()
    path.move(to: CGPoint(x: 0, y: 0))
    path.addArc(withCenter: CGPoint(x: cornerRadiusView, y: cornerRadiusView),
                radius: cornerRadiusView,
                startAngle: .pi * 3 / 2,
                endAngle: .pi,
                clockwise: false)
    path.addLine(to: CGPoint(x: 0, y: height))
    path.addLine(to: CGPoint(x: newWidth - cutPicture, y: height))
    path.addLine(to: CGPoint(x: newWidth, y: 0))
    path.addLine(to: CGPoint(x: cutPicture, y: 0))
    path.close()

    let shapeLayer = CAShapeLayer()
    shapeLayer.frame = customShape.bounds
    shapeLayer.path = path.cgPath
    shapeLayer.fillColor = UIColor.red.cgColor
    customShape.layer.mask = shapeLayer;
    customShape.layer.masksToBounds = true;
    customShape.image = userPicture
    customShape.contentMode = .scaleAspectFill

最终:

【讨论】:

    【解决方案2】:

    子视图的内容总是出现在其所有祖先的内容之上。您将userPicture 设为iv 的子视图,因此userPicture 的内容出现在iv 的内容之上。 userPicture的内容是猫图。 iv 的内容为紫框。所以猫的图片出现在紫色框的顶部。

    相反,将userPicture 设为父视图,并向其添加一个包含紫色框的frameView 子视图。

    【讨论】:

    • 感谢您的回复,当我这样做时,总是一样,图片溢出iv路径..
    猜你喜欢
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    相关资源
    最近更新 更多