dfox
dfox

Reputation: 13

iOS Stopping Image From Flipping?

I need some help with this code below. I have this set up currently so that an image turns from black to white, and then back from white to black on each click. The problem is that it's not just flipping the colours, it's actually flipping the image upside down as well. How do I make it stop flipping the image vertically? There are no orientation elements in there so I have been confused with what part is making it do this:

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

}

Upvotes: 1

Views: 327

Answers (1)

Taum
Taum

Reputation: 2551

It might be because CGContext has a different coordinate system, try adding this before your drawing code (before CGContextClipToMask):

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

If I remember correctly CGContext have the origin at the bottom right with positive Y going upwards, while UIKit uses the opposite (origin at top right, Y going downwards).

Upvotes: 4

Related Questions