问题描述
所以我习惯了UIImageView
,并且能够设置如何在其中显示图像的不同方式.例如AspectFill
模式等...
So I am used to UIImageView
, and being able to set different ways of how its image is displayed in it. Like for example AspectFill
mode etc...
我想在Mac应用程序上使用NSImageView
完成相同的操作.在这方面NSImageView
是否与UIImageView
类似,或者我将如何在NSImageView
中显示图像并选择显示图像的不同方式?
I would like to accomplish the same thing using NSImageView
on a mac app. Does NSImageView
work similarly to UIImageView
in that regard or how would I go about showing an image in an NSImageView
and picking different ways of displaying that image?
推荐答案
您可能会发现,将NSView
子类化并提供CALayer
可以满足您的需要,这要容易得多.这是NSView
子类的init
外观.
You may find it much easier to subclass NSView
and provide a CALayer
that does the aspect fill for you. Here is what the init
might look like for this NSView
subclass.
- (id)initWithFrame:(NSRect)frame andImage:(NSImage*)image
{
self = [super initWithFrame:frame];
if (self) {
self.layer = [[CALayer alloc] init];
self.layer.contentsGravity = kCAGravityResizeAspectFill;
self.layer.contents = image;
self.wantsLayer = YES;
}
return self;
}
请注意,设置图层,然后设置wantLayer的顺序非常重要(如果您先设置了wantLayer,则会获得默认的支持层).
Note that the order of setting the layer, then settings wantsLayer is very important (if you set wantsLayer first, you'll get a default backing layer instead).
您可以使用setImage
方法来简单地更新图层的内容.
You could have a setImage
method that simply updates the contents of the layer.
这篇关于NSImageView图像纵横比填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!