我想绘制一个按比例缩放和旋转90度的NSImage,但不断得到一个剪裁的结果图像。按比例缩放和旋转NSImage drawInRect
在一个NSView子类,这就是我现在做的事:
- (void) drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
NSImage* image = /* get image */;
CGRect drawRect = dirtyRect;
CGRect imageRect = [self proportionallyScale:image.size toSize:drawRect.size];
NSAffineTransform* rotation = [[NSAffineTransform alloc] init];
[rotation translateXBy:NSWidth(drawRect)/2 yBy:NSHeight(drawRect)/2];
[rotation rotateByDegrees:90];
[rotation translateXBy:-NSWidth(drawRect)/2 yBy:-NSHeight(drawRect)/2];
NSGraphicsContext* context = [NSGraphicsContext currentContext];
[context saveGraphicsState];
[rotation concat];
[image drawInRect:imageRect fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
[context restoreGraphicsState];
}
而且缩放逻辑:
- (CGRect) proportionallyScale:(CGSize)fromSize toSize:(CGSize)toSize
{
CGPoint origin = CGPointZero;
CGFloat width = fromSize.width, height = fromSize.height;
CGFloat targetWidth = toSize.width, targetHeight = toSize.height;
float widthFactor = targetWidth/width;
float heightFactor = targetHeight/height;
CGFloat scaleFactor = std::min(widthFactor, heightFactor);
CGFloat scaledWidth = width * scaleFactor;
CGFloat scaledHeight = height * scaleFactor;
if (widthFactor < heightFactor)
origin.y = (targetHeight - scaledHeight)/2.0;
else if (widthFactor > heightFactor)
origin.x = (targetWidth - scaledWidth)/2.0;
return {origin, {scaledWidth, scaledHeight}};
}
这里有没有施加旋转的结果(图像不是方形,红色背景呈现以显示视图的位置):
当我申请通过启用[rotation concat]
变换:
的问题是,图像的其偏移量应计算相对于所述旋转视区大小,而不是输入视图边界的缩放和。不过,我似乎无法想出正确计算这一点的逻辑。
任何人都可以请求帮助正确计算缩放和旋转图像的正确图像绘制矩形的逻辑吗?还是有更好的方法来解决整个问题?