时间:2010-07-24 03:12:38

标签: objective-c cocoa nsimage clipping image-clipping

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:0)

从macOS 10.6开始,这很容易。 此代码获取包含多个剪辑的主图像 并提取该母版的一部分以生成剪裁的图像。

// masterImage is the source image that contains multipe clips
NSImage *masterImage = [NSImage imageNamed:@"multiple_images.jpg"];
NSRect mFrame = NSMakeRect(0, 0, masterImage.size.width, masterImage.size.height);
NSImageRep *representation = [masterImage bestRepresentationForRect:mFrame
                                                            context:nil
                                                              hints:nil];

#define TARGET_IMAGE_SIZE    40 // NSImageView size (where the clip will be used)
NSSize targetSize = NSMakeSize(TARGET_IMAGE_SIZE, TARGET_IMAGE_SIZE);
NSImage *clippedImage = [NSImage imageWithSize:targetSize
                                       flipped:NO
                                drawingHandler:^BOOL(NSRect dstRect) {

    // set clipRect according to which clip you want:
    float xPos = 0; // compute these ...
    float yPos = 0; // ... positions of the clip within masterImage
    float clipSize = 50; // assumes each clip is square
    NSRect clipRect = NSMakeRect(xPos, yPos, clipSize, clipSize);

    BOOL ret = [representation drawInRect:dstRect
                                 fromRect:clipRect
                                operation:NSCompositingOperationCopy
                                 fraction:1.0 // alpha
                           respectFlipped:NO
                                    hints:nil];
    return ret; // ret from drawingHandler
}];

NSRect ivFrame = NSMakeRect( 0, 0, TARGET_IMAGE_SIZE, TARGET_IMAGE_SIZE);
NSImageView *clipImageView = [[NSImageView alloc] initWithFrame:ivFrame];
clipImageView.image = clippedImage;

提示:使用循环,布局为'N'NSImageViews (其中“ N”是片段数), 将每个剪辑提取到其中的imageViews中, 并弄清楚如何计算每个剪辑的xPos,yPos和剪辑大小(clipRect)。 一次查看所有剪辑会更容易。