使用多个剪切矩形在核心图形中创建拼贴画

6

我正在创建一个拼贴画,其中包含来自其他图像的元素。下面是一些ASCII艺术,以解释我的做法:

Given images A, B and C,
AAA, BBB, CCC
AAA, BBB, CCC
AAA, BBB, CCC

I take part of A, part of B and part of C as columns:

Axx, xBx, xxC
Axx, xBx, xxC
Axx, xBx, xxC

...and combine them in one image like this:

ABC
ABC
ABC

where the first 1/3rd of the image is a colum of A's pic, the middle is a column of B's pic and the last is a column of C's pic.

我有一些代码,但它只显示第一列而不是其余的列...我认为我需要以某种方式清除剪辑,但我不确定如何做或者这是否是最佳方法。

+ (UIImage *)collageWithSize:(NSInteger)size fromImages:(NSArray *)images {
    NSMutableArray *selectedImages = [NSMutableArray array];
    [selectedImages addObjectsFromArray:images];

    // use the selectedImages for generating the thumbnail
    float columnWidth = (float)size/(float)[selectedImages count];

    //create a context to do our clipping in
    UIGraphicsBeginImageContext(CGSizeMake(size, size));
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    for (int i = 0; i < [selectedImages count]; i++) {
        // get the current image
        UIImage *image = [selectedImages objectAtIndex:i];

        //create a rect with the size we want to crop the image to
        CGRect clippedRect = CGRectMake(i*columnWidth, 0, columnWidth, size);
        CGContextClipToRect(currentContext, clippedRect);

        //create a rect equivalent to the full size of the image
        CGRect drawRect = CGRectMake(0, 0, size, size);

        //draw the image to our clipped context using our offset rect
        CGContextDrawImage(currentContext, drawRect, image.CGImage);
    }

    //pull the image from our cropped context
    UIImage *collage = UIGraphicsGetImageFromCurrentImageContext();

    //pop the context to get back to the default
    UIGraphicsEndImageContext();

    //Note: this is autoreleased
    return collage;
}

我做错了什么?

另外,图片也是倒着画的。

2个回答

9

CGContextClipToRect将当前裁剪矩形与提供的参数相交。因此,第二次调用它时,您实际上将裁剪区域变为空。

没有办法恢复裁剪区域,除非恢复图形状态。因此,在循环顶部调用CGContextSaveGState,在底部调用CGContextRestoreGState

通过调整当前变换矩阵可以解决倒置的部分:调用CGContextTranslateCTM移动原点,然后调用CGContextScaleCTM翻转y轴。


1
CGContextSaveGStateCGContextRestoreGState正是我在寻找的。谢谢! - Sam Soffes

0
可以通过调用下面的方法来纠正颠倒的图像:
CGImageRef flip (CGImageRef im) {
CGSize sz = CGSizeMake(CGImageGetWidth(im), CGImageGetHeight(im));
UIGraphicsBeginImageContextWithOptions(sz, NO, 0);
CGContextDrawImage(UIGraphicsGetCurrentContext(),
                   CGRectMake(0, 0, sz.width, sz.height), im);
CGImageRef result = [UIGraphicsGetImageFromCurrentImageContext() CGImage];
UIGraphicsEndImageContext();
return result;

}

请参考下面的代码,了解您应该将此代码放在何处:

UIGraphicsBeginImageContextWithOptions(CGSizeMake(leftRect.size.width, leftRect.size.height), NO, 0);
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextDrawImage(con, leftRect,flip(leftReference));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接