【发布时间】:2017-12-06 06:16:49
【问题描述】:
我有一个UIImageView,有一个特定的图像。
我还有一个形状奇怪的UIBezierPath。
我想将图像剪切成该形状并返回该形状的新图像。
形式为:
func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
【问题讨论】:
标签: swift uiimageview uibezierpath
我有一个UIImageView,有一个特定的图像。
我还有一个形状奇怪的UIBezierPath。
我想将图像剪切成该形状并返回该形状的新图像。
形式为:
func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
【问题讨论】:
标签: swift uiimageview uibezierpath
您可以使用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
}
}
【讨论】:
使用 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
【讨论】:
您可以使用CAShapeLayer 来塑造图像...然后从该形状中获取图像...
UIGraphicsBeginImageContext(imgView.bounds.size);
[imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *mainImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
谢谢...
引用自here..
【讨论】: