在 Core Graphics 中创建拼贴的多个剪切矩形
Posted
技术标签:
【中文标题】在 Core Graphics 中创建拼贴的多个剪切矩形【英文标题】:Multiple Clipped Rects to Create Collage in Core Graphics 【发布时间】:2011-01-15 03:13:35 【问题描述】:我正在创建一个与其他图像中的元素相结合的拼贴画。这是一些 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;
我做错了什么?
PS 图片也是倒过来的。
【问题讨论】:
【参考方案1】:CGContextClipToRect
将当前剪切矩形与提供的参数相交。因此,第二次调用它时,您实际上是在将剪辑区域变为空。
如果不恢复图形状态,就无法恢复剪切区域。因此,请在循环顶部调用 CGContextSaveGState
,在底部调用 CGContextRestoreGState
。
可以通过调整当前变换矩阵来修复倒置的部分:调用CGContextTranslateCTM
移动原点,然后调用CGContextScaleCTM
翻转y轴。
【讨论】:
CGContextSaveGState
和 CGContextRestoreGState
是我想要的。谢谢!【参考方案2】:
可以通过调用以下方法来纠正倒置的图像:
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));
【讨论】:
以上是关于在 Core Graphics 中创建拼贴的多个剪切矩形的主要内容,如果未能解决你的问题,请参考以下文章