Why is my image upside down after using CGContextS

2019-05-21 01:32发布

问题:

I am trying to apply a color fill to the MKAnnotation. I found some code that pretty much works but for some reason the filled image is upside down after applying the fill to it.

Here is the current code that I am running on a map pin.

CGRect rect = CGRectMake(0, 0, self.image.size.width, self.image.size.height);
    UIGraphicsBeginImageContext(self.image.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToMask(context, rect, self.image.CGImage);
    CGContextSetFillColorWithColor(context, [[UIColor grayColor] CGColor]);
    CGContextFillRect(context, rect);
    CGContextRotateCTM(context, 90);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImage *flippedImage = [UIImage imageWithCGImage:img.CGImage
                                                scale:1.0 orientation:self.image.imageOrientation];

    self.image = flippedImage;

Here is what the pins look like after this code runs.

http://d.pr/i/UaPU

I was thinking that if I applied the current image orientation to the flippedImage that would do the trick but that did not work. I also tried setting self.image = img; and removing the flippedImage var completely but the result is still the same.

回答1:

CGContext coordinate system is flipped vertically in regard to UIView coordinate system. Just flip it like this: CGContextTranslateCTM(ctx, 0, imageHeight);, CGContextScaleCTM(ctx, 1, -1);