Reputation: 1
I have a UIImageView
, with a certain image.
I also have a UIBezierPath
in some strange shape.
I would like to cut the image to that shape and return a new image in that shape.
In the form of :
func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
Upvotes: 2
Views: 1354
Reputation: 16327
Use UIGraphicsImageRenderer to make an image with a clipping path. Here is a Playground:
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
Upvotes: 1
Reputation: 6459
You can use mask
to do so. Here's a quick example.
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
}
}
Upvotes: 4
Reputation: 880
You can use CAShapeLayer
for shaping the image... & then to get Image from that shape ...
UIGraphicsBeginImageContext(imgView.bounds.size);
[imgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *mainImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Thank You...
Referenced from here..
Upvotes: 0