我需要以下代码的帮助。我目前已设置此设置,以便图像从黑色变为白色,然后在每次单击时从白色变为黑色。问题是,它不仅仅是翻转颜色,而且实际上也是颠倒了图像。如何让它停止垂直翻转图像?那里没有方向元素,所以我对它做到这一点的部分感到困惑:
#define FLIP_BUTTON_TAG 200
#define FLIP_VUTTON_TAG2 300
- (void)viewDidLoad
{
[super viewDidLoad];
flipBtn.tag = FLIP_BUTTON_TAG;
}
UIImage* flippedImage;
if(flipBtn.tag==FLIP_BUTTON_TAG)
{
// set the fill color
UIImage *sourceImage1 = self.outletImageView.image;
CGRect rect = CGRectMake(0, 0, sourceImage1.size.width, sourceImage1.size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, rect, sourceImage1.CGImage);
CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGContextFillRect(context, rect);
sourceImage1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
flippedImage = sourceImage1;
flipBtn.tag = FLIP_VUTTON_TAG2;
}else{
UIImage* sourceImage1 = self.outletImageView.image;
CGRect rect = CGRectMake(0, 0, sourceImage1.size.width, sourceImage1.size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, rect, sourceImage1.CGImage);
CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextFillRect(context, rect);
sourceImage1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
flippedImage = sourceImage1;
flipBtn.tag = FLIP_BUTTON_TAG;
}
NSInteger index1 = [imgViewArray indexOfObject:self.outletImageView];
[imgViewArray removeObject:self.outletImageView];
self.outletImageView.image = flippedImage;
[imgViewArray insertObject:self.outletImageView atIndex:index1];
}
答案 0 :(得分:4)
可能是因为CGContext有一个不同的坐标系,尝试在绘图代码之前添加它(在CGContextClipToMask之前):
CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
如果我没记错的话CGContext的右下角有正Y向上,而UIKit使用相反的(右上角,Y向下)。