monsabre
monsabre

Reputation: 2099

get the actual display image size on NSImageView

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

Upvotes: 6

Views: 2572

Answers (2)

Cyrille
Cyrille

Reputation: 25144

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);
}

Upvotes: 8

Alburn
Alburn

Reputation: 1

Can you use the size property on NSImage to get the display size?

Upvotes: 0

Related Questions