trying to draw scaled UIImage in custom view, but nothing's rendering

Posted by Ben Collins on Stack Overflow See other posts from Stack Overflow or by Ben Collins
Published on 2010-04-10T16:31:34Z Indexed on 2010/04/10 16:33 UTC
Read the original article Hit count: 389

I've created a custom view class and right now just want to draw an image scaled to fit the view, given a UIImage. I tried just drawing the UIImage.CGImage, but as others have attested to on this site (and in the docs), that renders the image upside down.

So, at the suggestion of an answer I found to another question, I'm trying to draw it directly, but nothing is rendering in the view and I'm not sure why. Here's my drawing code:

- (void)drawRect:(CGRect)rect {
    // Drawing code
    [super drawRect:rect];

    if (self.originalImage) {
        [self drawImage];
    }
}

- (void) drawImage {
    if (CGSizeEqualToSize(originalImage.size, self.frame.size) == NO) {
        CGFloat scaleFactor = 1.0;
        CGFloat scaledWidth = 0.0;
        CGFloat scaledHeight = 0.0;
        CGPoint thumbPoint = CGPointMake(0.0, 0.0);

        CGFloat widthFactor = self.frame.size.width / originalImage.size.width;
        CGFloat heightFactor = self.frame.size.height / originalImage.size.height;

        if (widthFactor < heightFactor) {
            scaleFactor = widthFactor;
        } else {
            scaleFactor = heightFactor;
        }

        scaledWidth = originalImage.size.width * scaleFactor;
        scaledHeight = originalImage.size.height * scaleFactor;

        if (widthFactor < heightFactor) {
            thumbPoint.y = (self.frame.size.height - scaledHeight) * 0.5;
        } else if (widthFactor > heightFactor) {
            thumbPoint.x = (self.frame.size.width - scaledWidth) * 0.5;
        }

        UIGraphicsBeginImageContext(self.frame.size);
        CGRect thumbRect = CGRectZero;
        thumbRect.origin = thumbPoint;
        thumbRect.size.width = scaledWidth;
        thumbRect.size.height = scaledHeight;

        [originalImage drawInRect:thumbRect];
        self.scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    } else {
        self.scaledImage = originalImage;
    }   
}

My understanding (after studying this a bit) is that the UIGraphicsBeginImageContext function creates an offscreen for me to draw into, so now how do I render that context on top of the original one?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about quartz-graphics