如何裁剪UIImage?

Raj*_*ole 38 iphone uiimage

我开发了一个应用程序,我使用其像素处理图像,但在图像处理中需要花费很多时间.因此我想裁剪UIImage(只有图像的中间部分,即删除/裁剪图像的边界部分).我有开发代码,

- (NSInteger) processImage1: (UIImage*) image
{

 CGFloat width = image.size.width;
 CGFloat height = image.size.height;
 struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
 if (pixels != nil)
 {
  // Create a new bitmap
  CGContextRef context = CGBitmapContextCreate(
              (void*) pixels,
              image.size.width,
              image.size.height,
              8,
              image.size.width * 4,
              CGImageGetColorSpace(image.CGImage),
              kCGImageAlphaPremultipliedLast
              );
  if (context != NULL)
  {
   // Draw the image in the bitmap
   CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);
   NSUInteger numberOfPixels = image.size.width * image.size.height;

   NSMutableArray *numberOfPixelsArray = [[[NSMutableArray alloc] initWithCapacity:numberOfPixelsArray] autorelease];
}
Run Code Online (Sandbox Code Playgroud)

我如何拍摄(在外面裁剪)UIImage的中间部分?????????

Mih*_*hta 79

尝试这样的事情:

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
image = [UIImage imageWithCGImage:imageRef]; 
CGImageRelease(imageRef);
Run Code Online (Sandbox Code Playgroud)

注意:cropRect是较小的矩形,图像的中间部分......


M-V*_*M-V 40

我正在寻找一种方法来获得UIImage的任意矩形裁剪(即,子图像).

如果图像的方向不是UIImageOrientationUp,我尝试的大多数解决方案都不起作用.

例如:

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

通常,如果您使用iPhone相机,您将拥有其他方向,如UIImageOrientationLeft,并且您将无法使用上述方法获得正确的裁剪.这是因为使用了CGImageRef/CGContextDrawImage,它在坐标系方面与UIImage有所不同.

下面的代码使用UI*方法(没有CGImageRef),我用上/下/左/右方向图像测试了它,它看起来效果很好.


// get sub image
- (UIImage*) getSubImageFrom: (UIImage*) img WithRect: (CGRect) rect {

    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // translated rectangle for drawing sub image 
    CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, img.size.width, img.size.height);

    // clip to the bounds of the image context
    // not strictly necessary as it will get clipped anyway?
    CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));

    // draw image
    [img drawInRect:drawRect];

    // grab image
    UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return subImage;
}

  • 请注意,您只能在主线程上运行上面的代码.避免使用`UIGraphicsBeginImageContext`等的优点是绕过这个限制. (2认同)