简体   繁体   中英

Aspect Ratio issues when redrawing in Core Graphics context

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.

在此处输入图片说明

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.

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

包括此行并检查以上方法:-

[super drawRect:rect];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM