- (void)viewDidLoad {
[super viewDidLoad];
//如果要实现放大缩小窗口的时候,imageview中的图片随之变化大小的话,要实现一个监听窗口大小的动作,NSWindowDidResizeNotification
self.img.image = [self resizeImage:[NSImage imageNamed:@"0.88881.png"] size:NSMakeSize(self.img.frame.size.width, self.img.frame.size.height)];
}
- (NSImage*) resizeImage:(NSImage*)sourceImage size:(NSSize)size{
NSRect targetFrame = NSMakeRect(0, 0, size.width, size.height);
NSImage* targetImage = [[NSImage alloc] initWithSize:size];
NSSize sourceSize = [sourceImage size];
float ratioH = size.height/ sourceSize.height;
float ratioW = size.width / sourceSize.width;
NSRect cropRect = NSZeroRect;
if (ratioH >= ratioW) {
cropRect.size.width = floor (size.width / ratioH);
cropRect.size.height = sourceSize.height;
} else {
cropRect.size.width = sourceSize.width;
cropRect.size.height = floor(size.height / ratioW);
}
cropRect.origin.x = floor( (sourceSize.width - cropRect.size.width)/2 );
cropRect.origin.y = floor( (sourceSize.height - cropRect.size.height)/2 );
[targetImage lockFocus];
[sourceImage drawInRect:targetFrame
fromRect:cropRect //portion of source image to draw
operation:NSCompositeCopy //compositing operation
fraction:1.0 //alpha (transparency) value
respectFlipped:YES //coordinate system
hints:@{NSImageHintInterpolation:
[NSNumber numberWithInt:NSImageInterpolationLow]}];
[targetImage unlockFocus];
return targetImage;
}
Objective-C缩放image适应imageview的大小
最新推荐文章于 2025-02-18 11:02:09 发布
本文介绍如何在Objective-C中使用代码使图片自动缩放以适应UIImageView的大小,确保图片在显示时始终保持正确的比例,从而优化iOS应用的用户体验。
214

被折叠的 条评论
为什么被折叠?



