[英]How to rotate a NSTextView
I want to have rotatable text edit area like in Adobe Illustrator.我想拥有像 Adobe Illustrator 那样的可旋转文本编辑区域。 I tried several things including subclassing NSTextView and adding coordinate system rotation before the drawing code like this:我尝试了几件事,包括子类化 NSTextView 和在绘图代码之前添加坐标系旋转,如下所示:
@implementation MyNSTextView
-(void)drawRect:(NSRect)dirtyRect
{
NSAffineTransform * trafo = [NSAffineTransform transform];
[trafo rotateByDegrees:45];
[trafo concat];
[super drawRect:dirtyRect];
}
-(void)drawInsertionPointInRect:(NSRect)rect color:(NSColor *)color turnedOn:(BOOL)flag
{
NSAffineTransform * trafo = [NSAffineTransform transform];
[trafo rotateByDegrees:45];
[trafo concat];
[super drawInsertionPointInRect:rect color:color turnedOn:flag];
}
Which results in corrupted display of the text.这会导致文本显示损坏。 I also tried to implement the functionality myself by subclassing NSView and assembling the text architecture programmatically.我还尝试通过继承 NSView 并以编程方式组装文本架构来自己实现该功能。 I draw the string with the drawGlyphsForRange: method of my NSLayoutManager.我使用 NSLayoutManager 的 drawGlyphsForRange: 方法绘制字符串。 This partly works but gets complicated because I have to rotate the coordinates for the drawing and for handling the mouse clicks I have to convert the mouse location back to old coordinates.这部分可行但变得复杂,因为我必须旋转绘图的坐标并处理鼠标点击,我必须将鼠标位置转换回旧坐标。
So is this the best way to do it or is there something else?那么这是最好的方法还是有别的方法?
Edit: I now tried to use CALayer like this:编辑:我现在尝试像这样使用 CALayer:
@implementation MyNSTextView
-(id)initWithFrame:(NSRect)frameRect
{
self = [super initWithFrame:frameRect];
if (self) {
CALayer *myLayer = [CALayer layer];
myLayer.transform = CATransform3DMakeRotation(1.6,1,0,1.0);
[self setLayer:myLayer];
[self setWantsLayer:YES];
}
return self;
}
But this yields a TextView which doesn't show any text (only a cursor) and is not rotated.但这会产生一个 TextView 不显示任何文本(只有一个光标)并且不旋转。 Is there something else to add to make it work??是否还有其他内容可以添加以使其正常工作?
You are making it too complicated.你把它弄得太复杂了。 Simply set the rotation on the view itself:只需在视图本身上设置旋转:
[myView setFrameRotation:angleInDegrees];
There is also setFrameCenterRotation
, but that is supposed to work only for layer-backed views (which is OK).还有setFrameCenterRotation
,但这应该只适用于支持图层的视图(没关系)。
There is one caveat which I am still investigating myself: The blinking text cursor becomes really fat when the view is rotated.有一个警告我仍在调查自己:当视图旋转时,闪烁的文本 cursor 变得非常胖。
Why not make the views layer-backed?为什么不让视图层支持? You can then just apply an affine transform to the view's layer.然后,您可以将仿射变换应用到视图的图层。
yourView.layer.transform = CATransform3DMakeRotation(M_PI_4, 0, 0, 1.0);
The problem is that you're creating an NSAffineTransform
, but you're not attaching it to your text view.问题是您正在创建一个NSAffineTransform
,但您没有将它附加到您的文本视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.