我正在 Xcode 中使用 Objective-C 编写一个 OSX 应用程序。我有一个窗口,里面有一个 NSView,并且 NSView 应该使用包含 NSNumbers 的 NSMutableArray 中的数据在网格上绘制相应的图像,以便在 0,0 处绘制图像; 32,0; 64,0。 。 。 0,32; 32,32;等等。因此,数组的计数是网格的宽*高,在本例中为 21*21 或 441。
您左键单击以“放置”图像,这实际上意味着根据您单击的位置更新数组,然后调用 setNeedsDisplay:YES 以便它重新绘制自身以反射(reflect)更新的数组。到目前为止,我可以让它正确地根据数组绘制图像。
但是,当您右键单击时,它应该将特定网格槽中的图像旋转一定的量。我在这里遇到的唯一问题是弄清楚如何在正确的位置实际绘制旋转图像。它们应该绕其中心点旋转,这将是相对坐标 16,16(所有图像的大小均为 32x32 像素)。事实上,我的代码是:
- (void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
//Black background
[[NSColor blackColor] setFill];
NSRectFill(dirtyRect);
// Drawing code here.
NSRect rectToDraw = CGRectMake(0,0,32,32);
NSInteger imageIndex = 0;
NSImage *imageToDraw = nil;
for (int i = 0; i < [objDataArray count]; i++) {
//Loop through data array and draw each image where it should be
if ([objDataArray objectAtIndex:i]==[NSNull null]) continue; //Don't draw anything in this slot
//Math to determine where to draw based on the current for loop index
//0 = 0,0; 1 = 32,0 . . . 20 = 640,0; 21 = 0,32; etc. (grid is 21x21)
rectToDraw.origin.x = (i % 21)*32;
rectToDraw.origin.y = floor(i/21)*32;
//Get the data at this index in the data array
imageIndex = [((NSNumber*)[objDataArray objectAtIndex:i]) integerValue];
//Use the retrieved number to get a corresponding image
imageToDraw = (NSImage*)[objImagesArray objectAtIndex:imageIndex];
//Draw that image at the proper location
[imageToDraw drawInRect:rectToDraw];
}
}
因此,旋转量(以度为单位)由变量rotationAmount 指定。如何更改drawInRect行(右大括号之前的最后一行)以便图像绘制在由rectToDraw指定的正确位置,但绕其中心旋转rotationAmount度数?
谢谢。
最佳答案
您不会像这样绘制旋转的图像。您变换坐标空间,然后绘制图像。
[NSGraphicsContext saveGraphicsState];
NSAffineTransform* xform = [NSAffineTransform transform];
// Translate the image's center to the view origin so rotation occurs around it.
[xform translateXBy:-NSMidX(rectToDraw) yBy:-NSMidY(rectToDraw)];
[xform rotateByDegrees:rotationAmount];
[xform concat];
[imageToDraw drawInRect:NSOffsetRect(rectToDraw, -NSMidX(rectToDraw), -NSMidY(rectToDraw))];
[NSGraphicsContext restoreGraphicsState];
我有可能向后转换。我总是忘记它的走向(如果它正在改变 View 或内容)。如果您的图像进入了梦幻般的境界,请更改翻译的符号。
关于objective-c - 如何在 OSX 应用程序中使用 DrawRect 旋转直接绘制到 NSView 的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23944368/