简体   繁体   中英

Crop image before show in a UIImageView

I'm my app I need to crop and image downloaded from internet. I download the image using this method:

- (void) loadImageFromWeb {
    NSURL* url = [NSURL URLWithString:self.imageURL];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];


    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response,
                                               NSData * data,
                                               NSError * error) {
                               if (!error){
                                   UIImage* image = [[UIImage alloc] initWithData:data];
                                   [self.imageViewEpisode setImage:image];
                               }

                           }];
}

How I can crop it?

Define a rect, this rect will be the crop area of your image.

CGRect croprect  = CGRectMake(x,y,width, height);

CGImageRef subImage = CGImageCreateWithImageInRect (yourimage,croprect);

Here we have used CoreGraphics to create a sub image from your image.

Creates a bitmap image using the data contained within a subregion of an existing bitmap image.

CGImageRef CGImageCreateWithImageInRect (
   CGImageRef image,
   CGRect rect
);

Parameters

image

    The image to extract the subimage from. 
rect

    A rectangle whose coordinates specify the area to create an image from.

Return Value

A CGImage object that specifies a subimage of the image. If the rect parameter defines an area that is not in the image, returns NULL.

Finally generate image,

UIImage *newImage = [UIImage imageWithCGImage:subImage];

There are multiple libraries that can do that for you. You can either pick one and work with it, or study a couple and understand how it's done.

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