3

CGContext を使用して UIImage (.jpg 形式) をトリミングする単純な UIApplication を開発しています。これまでに開発したコードは次のとおりです。

CGImageRef graphicOriginalImage = [originalImage.image CGImage];

UIGraphicsBeginImageContext(originalImage.image.size);

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGBitmapContextCreateImage(graphicOriginalImage);

CGFloat fltW = originalImage.image.size.width;
CGFloat fltH = originalImage.image.size.height;
CGFloat X = round(fltW/4); 
CGFloat Y =round(fltH/4);
CGFloat width = round(X + (fltW/2));
CGFloat height = round(Y + (fltH/2));   

CGContextTranslateCTM(ctx, 0, image.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGRect rect = CGRectMake(X,Y ,width ,height); 
CGContextDrawImage(ctx, rect, graphicOriginalImage);

croppedImage = UIGraphicsGetImageFromCurrentImageContext();

return croppedImage;

上記のコードは問題なく動作しますが、画像をトリミングできません。元の画像メモリとトリミングされた画像メモリ i は同じになります(元の画像メモリと同じです)。上記のコードは、画像をトリミングするのに適しています??????????????????

4

2 に答える 2

15

画像を 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/から。

于 2010-12-12T07:58:00.920 に答える
-1

画像を描画するために作成するコンテキストは、元の画像と同じサイズです。そのため、同じサイズになっています。

車輪の再発明をしたくない場合は、GoogleCodeのTouchCodeプロジェクトをご覧ください。その仕事をするUIImageカテゴリがあります(UIImage_ThumbnailExtensions.mを参照)。

于 2010-04-16T18:47:40.757 に答える