objective-c - 如何在 OSX 应用程序中使用 DrawRect 旋转直接绘制到 NSView 的图像?

标签 objective-c macos drawrect nsimage drawinrect

我正在 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/

相关文章:

php - 在 Mac OS X 10.7.3(默认 php)下安装和启用 APC 缓存

swift - 基于选中状态聚焦文本字段和移除焦点

ios - 定义了另一个 init 方法,但是 initWithNibName :bundle is still called by system

ios - 如何实现 NSUserDefaults 来保存首选项

ios - 委托(delegate)方法不会自动完成

macos - 无法找出 Mac OS X 中 PostgreSQL 的数据目录

android - 多个矩形不在 Canvas 上绘制

ios - 使用drawRect创建的水平动画进度条

ios - iOS 中的绘制矩形

ios - 我的 iOS 框架中的异常显示私有(private)代码?