多个剪切的矩形在核心图形中创建拼贴 [英] Multiple Clipped Rects to Create Collage in Core Graphics
问题描述
我正在创建一个拼贴与其他图像中的元素相结合。这里有一些ASCII艺术来解释我在做什么:
I am creating a collage combined with elements from other images. Here is some ASCII art to explain what I am doing:
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.
我写了一些代码,但它只显示第一列而不是其余的......我想我必须以某种方式清除剪辑,但我不知道该怎么做或者这是否是最好的方法。
I have some code written but it is only showing the first column and not the rest… I think I have to clear the clipping somehow, bt I am not sure of how to do it or whether this is even the best approach.
+ (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图像也正在颠倒。
PS the image is drawing upside down too.
推荐答案
CGContextClipToRect
将当前剪切矩形与提供的参数相交。因此,第二次调用它时,您实际上将剪切区域变为空。
CGContextClipToRect
intersects the current clipping rectangle with the argument provided. So the second time you call it, you are effectively turning your clipping region to nothing.
如果不恢复图形状态,则无法恢复剪切区域。因此,在循环顶部调用 CGContextSaveGState
,在底部调用 CGContextRestoreGState
。
There is no way to restore the clipping region without restoring the graphics state. So, make a call to CGContextSaveGState
at the top of your loop and a call to CGContextRestoreGState
at the bottom.
可以通过调整当前转换矩阵来修复颠倒部分:调用 CGContextTranslateCTM
移动原点然后 CGContextScaleCTM
翻转y轴。
The upside-down part can be fixed by adjusting the current transformation matrix: call CGContextTranslateCTM
to move the origin and then CGContextScaleCTM
to flip the y-axis.
这篇关于多个剪切的矩形在核心图形中创建拼贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!