How can i extract an UIImage with an path?
I need to get the content that’s inside the path into a new UIImage. What I need is the content of a rotated rectangle. This is the code that I use to get the corners of the rectangle. (x,y = center of image. width, height of image).
UIBezierPath* aPath = [UIBezierPath bezierPath];
//1
[aPath moveToPoint:CGPointMake(
x+(width/2)*cosf(A)-(height/2)*sinf(A),
y+(height/2)*cosf(A)+(width/2)*sinf(A))];
NSLog(@"%f, %f", x+(width/2)*cosf(A)-(height/2)*sinf(A),
y+(height/2)*cosf(A)+(width/2)*sinf(A));
//2
[aPath moveToPoint:CGPointMake(
x-(width/2)*cosf(A)-(height/2)*sinf(A),
y+(height/2)*cosf(A)-(width/2)*sinf(A))];
NSLog(@"%f, %f", x-(width/2)*cosf(A)-(height/2)*sinf(A),
y+(height/2)*cosf(A)-(width/2)*sinf(A));
//3
[aPath moveToPoint:CGPointMake(
x-(width/2)*cosf(A)+(height/2)*sinf(A),
y-(height/2)*cosf(A)-(width/2)*sinf(A))];
NSLog(@"%f, %f", x-(width/2)*cosf(A)+(height/2)*sinf(A),
y-(height/2)*cosf(A)-(width/2)*sinf(A));
//4
[aPath moveToPoint:CGPointMake(
x+(width/2)*cosf(A)+(height/2)*sinf(A),
y-(height/2)*cosf(A)+(width/2)*sinf(A))];
NSLog(@"%f, %f", x+(width/2)*cosf(A)+(height/2)*sinf(A),
y-(height/2)*cosf(A)+(width/2)*sinf(A));
//5
[aPath moveToPoint:CGPointMake(
x+(width/2)*cosf(A)-(height/2)*sinf(A),
y+(height/2)*cosf(A)+(width/2)*sinf(A))];
NSLog(@"%f, %f", x+(width/2)*cosf(A)-(height/2)*sinf(A),
y+(height/2)*cosf(A)+(width/2)*sinf(A));
[aPath closePath];
I was thinking something like this: A picture of the problem.
(The shape is different here.) I want that yellow part to be a new UIImage.
Use your
UIBezierPathas a clipping path. There is theaddClipmethod for that.See the Quartz2D Programming Guide, especially this part for details.
The idea is to create a new Bitmap context, apply the clipping using your path, then draw the image (that will thus get clipped) on this bitmap context and finally generate an UIImage from it.
Moreover, instead of making some maths by yourself to rotate your
CGRectyou want to use for clipping, you should create aCGRectwithout any rotation, and useCGAffineTransformto rotate it. This will avoid the need to do the computation by yourself usingcos/sinfunctions and make your code easier to read.[EDIT] Here is a full example to:
I did check it and works like a charm.