2011-10-28 33 views
5

tôi đã sử dụng mã dưới đây để hiển thị một hình ảnhcó được kích thước hình ảnh hiển thị thực tế trên NSImageView

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

các NSImageView sẽ thay đổi kích thước NSimage tự động

enter image description here

Làm thế nào để có được kích thước hiển thị thực tế của NSImage?

Chào mừng mọi nhận xét

Trả lời

4

Tôi có một phương pháp như vậy dành cho iOS, bạn có thể thích ứng với nó:

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

Bạn có thể sử dụng thuộc tính kích thước trên NSImage để có kích thước hiển thị không?

+0

Không thường, đó là kích thước gốc của hình ảnh thực tế, không phải là kích thước mà nó hiện đang render trong giao diện , nơi mà nó có khả năng thu nhỏ kích thước khác nhau. –

Các vấn đề liên quan