如何在iPhone中裁剪UIImage? [英] How to crop the UIImage in iPhone?

查看:94
本文介绍了如何在iPhone中裁剪UIImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我在UIImageView中设置了一个图像,UIImageView的大小为320 x 170.但原始图像的大小为320 x 460.所以如何裁剪此图像并在UIImageView中显示。

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.

推荐答案

以下是将图像裁剪为CGRect的好方法:

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;

}

或另一种方式:

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

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

  UIImage *cropped = [UIImage imageWithCGImage:imageRef];

  CGImageRelease(imageRef);


      return cropped;
    

}

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

这篇关于如何在iPhone中裁剪UIImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆