Reputation: 4211
I have an UIImage and a CGPoint which tells me in what direction I should move it to create another image. The background can be anything.
Give the initial UIImage how I can create the new one? What is the most efficient way of doing it?
Here is what I'm doing:
int originalWidth = image.size.width;
int originalHeight = image.size.height;
float xDifference = [[coords objectAtIndex:0] floatValue];
float yDifference = [[coords objectAtIndex:1] floatValue];
UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 240, originalWidth, originalHeight)];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.contentMode = UIViewContentModeTopLeft;
CGRect imageFrame = imageView.frame;
imageFrame.origin.x = xDifference;
imageFrame.origin.y = -yDifference;
imageView.frame = imageFrame;
UIGraphicsBeginImageContext(tempView.bounds.size);
[tempView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
Is there a more optimal version?
Upvotes: 2
Views: 5940
Reputation: 73588
You can use CGImageCreateWithImageInRect(). You can get a CGImage
from a UIImage
with the property of the same name.
Basically what you end up doing is apply masks to the existing image to extract the portions you need. Like so -
myImageArea = CGRectMake(xOrigin, yOrigin, myWidth, myHeight);//newImage
mySubimage = CGImageCreateWithImageInRect(oldImage, myImageArea);
myRect = CGRectMake(0, 0, myWidth*2, myHeight*2);
CGContextDrawImage(context, myRect, mySubimage);
This post gives a good idea of how to use this property.
Upvotes: 8