我有UIImageView
,有一定的图片。
我的UIBezierPath
也有一些奇怪的形状。
我想将图像剪切成该形状并返回该形状的新图像。
以下列形式:
func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
答案 0 :(得分:2)
您可以使用mask
来执行此操作。这是一个简单的例子。
class ViewController: UIViewController {
var path: UIBezierPath!
var touchPoint: CGPoint!
var startPoint: CGPoint!
var imageView = UIImageView(image: #imageLiteral(resourceName: "IMG_0715"))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
startPoint = touch.location(in: view)
path = UIBezierPath()
path.move(to: startPoint)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
touchPoint = touch.location(in: view)
}
path.addLine(to: touchPoint)
startPoint = touchPoint
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
cut()
}
private func cut() {
guard let path = path else { return }
imageView = imageView.getCut(with: path)
}
}
extension UIImageView {
func getCut(with bezier: UIBezierPath) -> UIImageView {
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezier.cgPath
self.layer.mask = shapeLayer
return self
}
}
答案 1 :(得分:0)
您可以使用CAShapeLayer
来塑造图像......&amp;然后从那个形状中获取图像...
UIGraphicsBeginImageContext(imgView.bounds.size);
[imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *mainImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
谢谢......
引自here ..
答案 2 :(得分:0)
使用UIGraphicsImageRenderer制作带剪切路径的图像。这是一个游乐场:
import PlaygroundSupport
import UIKit
let imageToCrop = UIImage(named: "test.jpg")!
let size = imageToCrop.size
let cutImage = UIGraphicsImageRenderer(size: size).image { imageContext in
let context = imageContext.cgContext
let clippingPath = UIBezierPath(ovalIn: CGRect(origin: .zero, size: size)).cgPath
context.addPath(clippingPath)
context.clip(using: .evenOdd)
imageToCrop.draw(at: .zero)
}
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
imageView.image = cutImage
PlaygroundPage.current.liveView = imageView