Question

I am redrawing images in a CGContextRef graphics context, however, when I draw the images, their aspect ratio is wrong. In the picture below, the graphics context is the black square (a separate UIView class), and the pictures being displayed are selected from the red carousel below it. I've looked at a bunch of posts, but can't figure out where to fix it.

enter image description here

Here is my drawRect method. I don't know where I can set the contentMode, since there is not UIImageView, only UIImages.

- (void)drawRect:(CGRect)rect
{
    NSMutableDictionary *dna = _mini.dna;
    NSString *directory = @"FacialFeatures";

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, self.bounds);

    //flip the coordinates for Core Graphics coordinates
    CGContextScaleCTM(context, 1, -1);
    CGContextTranslateCTM(context, 0, -self.bounds.size.height);

    for (id key in dna) {
        NSString *value = [dna objectForKey:key];
        if (![value isEqualToString:@""]) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%@/%@/%@", directory, key, value]];
            CGContextDrawImage(context, rect, image.CGImage);
        }
    }
}

For bonus help, I also don't know why the background of the Graphics Context is black. I've tried setting it in interface builder and in my init method but it seems all settings are ignored. Many thanks.

Was it helpful?

Solution

You have cleared the rect using

CGContextClearRect(context, self.bounds);

This will make your context and view transparent so, Check your super view's color may be it's black. If you want it white you can do like

CGContextClearRect(context, rect);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);

Reason of image stretching

CGContextDrawImage will scale image to fit into specified rect. So,try to provide a rect in a such a way that it's aspect ratio will be maintain.

Here I have provide few link which using some calculation to calculate rect or size
Resize image with keeping aspect ratio
UIImage aspect fit

OTHER TIPS

Include this line and check in the above method:-

[super drawRect:rect];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top