如何在NSView中旋转文本?(Mac OS,可可,Swift) [英] How to rotate text in NSView? (Mac OS, Cocoa, Swift)
问题描述
我是Mac OS 10.11(不是iOS)的Cocoa/Swift应用程序的新手.我创建了一个 NSView
,其大小为 A4
纸,并使用 drawRect()中的
.到目前为止,一切正常. NSString.drawAtPoint
绘制了一些简单的线条和一些文本
I am new to Cocoa/Swift applications for Mac OS 10.11 (Not iOS). I created an NSView
with the size of A4
paper, drew some simple lines and some text using NSString.drawAtPoint
within drawRect()
. So far it works.
但是,有时我需要将几个字符旋转90度,并且一些文本需要在X或Y方向上缩放.那是我不知道怎么做的地方.请有人能告诉我如何实现这些目标吗?
However, from time to time, I need a few characters to be turned 90 degrees, and some text needs to be scaled at X, or Y direction. That is where I don't know how to do it. Please can someone tell me how to achieve these?
非常感谢.
推荐答案
您可以使用 NSAffineTransform
.这段代码绘制了一个顺时针旋转90度的大写字母"A":
You can use NSAffineTransform
. This code draws a capital "A" rotated 90 degrees clockwise:
[NSGraphicsContext saveGraphicsContext]; // save current affine transform
[[[NSAffineTransform transform] rotateByDegrees:90] concat];
[@"A" drawAtPoint:point withAttributes:@{}];
[NSGraphicsContext restoreGraphicsContext]; // restore original transform
请注意, rotateByDegrees
会围绕原点旋转图形上下文.如果要围绕其他点旋转,则需要添加几个平移.这个 concat
是一个围绕 rotatePoint
旋转的变换:
Note that rotateByDegrees
rotates the graphics context around the origin point. If you want to rotate around some other point, you need to add a couple of translations. This concat
s a transform that rotates around rotatePoint
:
NSAffineTransform *transform = [NSAffineTransform transform];
[transform translateXBy:rotatePoint.x yBy:rotatePoint.y];
[transform rotateByDegrees:90];
[transform translateXBy:-rotatePoint.x yBy:-rotatePoint.y];
[transform contat];
这篇关于如何在NSView中旋转文本?(Mac OS,可可,Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!