1

ねえ、私は画像を保存するための例を調べましたが、その後、画面の一部だけを保存したいと思いました. 画像の左上隅から始まる部分を保存することができましたが、実際には画面の中央を保存したいです。画像の一部のみを保存する魔法は、次のように特定のサイズでグラフィック コンテキストを設定することです。

 UIGraphicsBeginImageContextWithOptions(CGSizeMake(300, 300), YES, 5.0f);

サイズの代わりに CGRect を使用する方法があるのではないかと思いましたが、エラーが発生します。他の試みや考えはありますか?スクリーンショットのピクセルを調べて、必要なピクセルを取得して、そこから新しい画像を作成する必要がありますか?

4

3 に答える 3

1

このために私が書いたこのメソッドは完全に機能します:

+ (UIImage*) getTheArea:(CGRect)area inView:(UIView*)view{

    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(area.size.width, area.size.height), NO, [UIScreen mainScreen].scale);
    else
        UIGraphicsBeginImageContext(view.bounds.size);

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, -area.origin.x, -area.origin.y);    // <-- shift everything up by 40px when drawing.
    [view.layer renderInContext:c];
    UIImage* thePrintScreen = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return thePrintScreen;
}

たとえば、(100,50,100,100) で、メイン ビューの印刷画面を作成する場合

UIImage* image = [self getTheArea:CGRectMake(100,50,100,100) inView:view];
于 2013-10-21T09:31:41.863 に答える
1

C4Image オブジェクトでこれを行うには、incmiko の回答を次のように変更します。

#import "C4Workspace.h"

@implementation C4WorkSpace{
    C4Image *image;
    C4Image *croppedImage;
}

-(void)setup {
    image=[C4Image imageNamed:@"C4Sky.png"];
    image.origin=CGPointMake(0, 20);

    croppedImage = [self cropImage:image toArea:CGRectMake(150,50,100,100)];
    croppedImage.origin = CGPointMake(20, 360);
    [self.canvas addObjects:@[image,croppedImage]];
}

-(C4Image *)cropImage:(C4Image *)originalImage toArea:(CGRect)rect{
    //grab the image scale
    CGFloat scale = originalImage.UIImage.scale;

    //begin an image context
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, scale);

    //create a new context ref
    CGContextRef c = UIGraphicsGetCurrentContext();

    //shift BACKWARDS in both directions because this moves the image
    //the area to crop shifts INTO: (0, 0, rect.size.width, rect.size.height)
    CGContextTranslateCTM(c, -rect.origin.x, -rect.origin.y);

    //render the original image into the context
    [originalImage renderInContext:c];

    //grab a UIImage from the context
    UIImage *newUIImage = UIGraphicsGetImageFromCurrentImageContext();

    //end the image context
    UIGraphicsEndImageContext();

    //create a new C4Image
    C4Image *newImage = [C4Image imageWithUIImage:newUIImage];

    //return the new image
    return newImage;
}
@end

コード内のコメント以外にも、注意すべき点がいくつかあります。

  1. トリミングしている「領域」は、常にトリミングしている「画像」を参照しています。そのため、画像からトリミングする場合{150,50}、画像の原点が にある場合、CANVAS から{20,20}トリミングしているように見えます。{170,70}

  2. C4Imageオブジェクトには実際にメソッドrenderInContext:があるため、画像のレイヤーからこれを行う必要はありません。

  3. C4Imageオブジェクトはオブジェクトをラップ します。これが、現在のコンテキストから取得した をUIImage使用して新しいオブジェクトを構築する理由です。UIImage

于 2013-10-22T20:59:46.190 に答える