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?
You can use
CGImageCreateWithImageInRect(). You can get aCGImage
from aUIImage
with theproperty 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 -
This post gives a good idea of how to use this property.