ios - 在 UIGraphicsImageRenderer 中添加 UIImage
问题描述
我是 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
图像时,不要使用路径的边界......
这就是我所拥有的:
这就是我想要的:
(用猫图片替换白色背景):
我究竟做错了什么?
解决方案
我用另一个解决方案解决了我的问题(将路径添加到 shapeLayer 并将其添加到 a 的掩码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
最终的 :
推荐阅读
- java - 应用程序停止工作:单击列表选项时猜词游戏停止工作
- visual-c++ - Visual Stidio 2015 # pragma comment (linker, "/EXPORT options
- scala - 构建一个大任务计算与同步执行几个步骤相比如何?
- c# - 在特定日期使程序崩溃
- mysql - SQL,用电子邮件替换部分字符串
- java - 构建时错误:prolog 中不允许内容
- selenium-chromedriver - 即使在使用 driver.quit() 之后,chromedriver.exe 进程仍然存在于任务管理器中
- php - 通过 PHP 上传大文件
- windows - ec2 用户数据跳过 Powershell 块
- ios - 如何在 Swift 中制作单例 AdMob 插页式广告?