Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the actual display image size on NSImageView

Tags:

cocoa

I used the codes below to display an image

NSImage *image = [[[NSImage alloc] initWithContentsOfURL:url] autorelease];
NSImageView *newImageView = nil;
newImageView = [[NSImageView alloc] initWithFrame:[self bounds]];
[newImageView setImage:image];
[newImageView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

the NSImageView will resize the NSimage automatically

enter image description here

How to get the actual display size of the NSImage?

Welcome any comment

like image 884
monsabre Avatar asked Oct 28 '11 13:10

monsabre


1 Answers

I have such a method for iOS, you may be able to adapt it:

@implementation UIImageView (additions)
- (CGSize)imageScale {
    CGFloat sx = self.frame.size.width / self.image.size.width;
    CGFloat sy = self.frame.size.height / self.image.size.height;
    CGFloat s = 1.0;
    switch (self.contentMode) {
        case UIViewContentModeScaleAspectFit:
            s = fminf(sx, sy);
            return CGSizeMake(s, s);
            break;

        case UIViewContentModeScaleAspectFill:
            s = fmaxf(sx, sy);
            return CGSizeMake(s, s);
            break;

        case UIViewContentModeScaleToFill:
            return CGSizeMake(sx, sy);

        default:
            return CGSizeMake(s, s);
    }
}

- (CGRect)imageRect {
    CGSize imgScale = [self imageScale];
    return CGRectCenteredInCGRect(CGRectFromCGSize(CGSizeScale(self.image.size, imgScale.width, imgScale.height)), self.frame);
}
@end



CGRect CGRectCenteredInCGRect(CGRect inner, CGRect outer) {
    return CGRectMake((outer.size.width - inner.size.width) / 2.0, (outer.size.height - inner.size.height) / 2.0, inner.size.width, inner.size.height);
}
like image 73
Cyrille Avatar answered Oct 15 '22 06:10

Cyrille