Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In my application, I have set one image in UIImageView and the size of UIImageView is 320 x 170. but the size of original image is 320 x 460. so how to crop this image and display in UIImageView.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
813 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here is a good way to crop an image to a CGRect:

- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect

{

   //create a context to do our clipping in

   UIGraphicsBeginImageContext(rect.size);

   CGContextRef currentContext = UIGraphicsGetCurrentContext();

   //create a rect with the size we want to crop the image to
   //the X and Y here are zero so we start at the beginning of our
   //newly created context

   CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);

   CGContextClipToRect( currentContext, clippedRect);

   //create a rect equivalent to the full size of the image
   //offset the rect by the X and Y we want to start the crop
   //from in order to cut off anything before them

   CGRect drawRect = CGRectMake(rect.origin.x * -1,
                                rect.origin.y * -1,
                                imageToCrop.size.width,
                                imageToCrop.size.height);

   //draw the image to our clipped context using our offset rect

   CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);

   //pull the image from our cropped context

   UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();

   //pop the context to get back to the default

   UIGraphicsEndImageContext();

   //Note: this is autoreleased

   return cropped;

}

Or another way:

- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect?     

{
  CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);?    

  UIImage *cropped = [UIImage imageWithCGImage:imageRef];

  CGImageRelease(imageRef);

?      return cropped;?    

}

From http://www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...