简体   繁体   中英

UIImage by selecting part of another UIImage

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM