1

我需要一些关于下面这段代码的帮助。我目前有这个设置,以便图像从黑色变为白色,然后在每次点击时从白色变为黑色。问题是它不仅仅是翻转颜色,它实际上也翻转了图像。如何让它停止垂直翻转图像?那里没有方向元素,所以我一直很困惑是什么部分使它这样做:

#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];

}
4

1 回答 1

4

这可能是因为 CGContext 具有不同的坐标系,请尝试在您的绘图代码之前添加它(在 CGContextClipToMask 之前):

CGContextTranslateCTM(context, 0, rect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);

如果我没记错的话,CGContext 的原点位于右下角,正 Y 向上,而 UIKit 使用相反的(原点在右上角,Y 向下)。

于 2013-10-31T19:54:49.567 回答