如何在OSX应用程序中使用DrawRect将图像直接旋转到NSView?

时间:2014-05-29 22:57:35

标签: objective-c macos drawrect nsimage drawinrect

我正在使用Objective-C在Xcode中编写OSX应用程序。我有一个窗口,里面有一个NSView,并且NSView应该使用来自包含NSNumbers的NSMutableArray的数据在网格上绘制相应的图像,以便在0,0处绘制图像; 32,0; 64,0。 。 。 0,32; 32,32;因此,数组的计数是网格的W * H,在这种情况下是21 * 21或441。

您左键单击以“放置”图像,这实际上只是意味着根据您单击的位置更新数组,然后调用setNeedsDisplay:YES以便重绘自身以反映更新的数组。到目前为止,我可以让它根据数组正确绘制图像。

但是,当您右键单击时,它应该将特定网格插槽中的图像旋转一定量。我在这里遇到的唯一问题是弄清楚如何在适当的位置实际绘制旋转的图像。它们应围绕它们的中心点旋转,这将是相对坐标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度数围绕其中心旋转?

感谢。

1 个答案:

答案 0 :(得分:2)

您不能将图像旋转,因此。您可以变换坐标空间,然后绘制图像。

[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];

我有可能向后转换。我总是忘记它的方式(如果它改变了视图或内容)。如果您的图像变为永不落地,请更改翻译的标志。