如何在Mac OS X中的CALayer中绘制旋转文本

时间:2018-02-22 20:50:09

标签: objective-c calayer

我在Mac OS X上有一个使用多个CALayer的飞机绘图应用程序。我想绘制正确旋转的跑道号,但我不明白为什么我的旋转不起作用。我的观点被翻转了。

这是我的代码:

void drawTextAtAngle (CGContextRef context, NSString *label, NSPoint pt, double angle)
{    
   CGContextSaveGState (context);

   /*
    * Draw a blob for the center - this proves 'pt' is at the correct place
    */
   CGContextSetLineWidth (context, 2.5);
   NSRect rect = CGRectMake (pt.x - 5.0, pt.y - 5.0, 5.0 * 2.0, 5.0 * 2.0);
   CGContextSetRGBStrokeColor (context, 50.0 / 255.0, 118.0 / 255.0, 193.0 / 255.0, _lineAlpha);
   CGContextSetRGBFillColor (context, 50.0 / 255.0, 118.0 / 255.0, 193.0 / 255.0, _lineAlpha);
   CGContextStrokeEllipseInRect (context, rect);

/*
 * Tried some of this with mixed results.
 */
//   CGAffineTransform transform = CGAffineTransformMake (1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
//   transform = CGAffineTransformTranslate (transform, pt.x, pt.y);
//   CGContextSetTextMatrix (context, transform);
//   CGContextRotateCTM (context, angle);


   /*
    * Don't know what this does but if not here text draws backwards.
    */
   CGAffineTransform transform = CGAffineTransformMake (1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
   CGContextSetTextMatrix (context, transform);

  /*
   * This rotates the view but around the centre bit I need to rotate it
   * around 'pt'.
   */
  CGContextRotateCTM (context, angle);

//CGAffineTransform transform = CGAffineTransformMakeRotation (M_PI / 2.0);
//CGAffineTransform transform2 = CGAffineTransformMakeRotation (angle);
//[self setAffineTransform:transform];
//   CGContextSetTextMatrix (context, transform2);


  /*
   * Some of this is apparently deprecated in 10.10.
   */
  CGContextSelectFont (context, "Helvetica", 14.0, kCGEncodingMacRoman);
  CGContextShowTextAtPoint (context, pt.x, pt.y, [label UTF8String], [label length]);

  CGContextRestoreGState (context);
  }

这是绘制的: Image

'29'跑道标签应该在蓝色的小圆圈上面,上面的代码评论“绘制blob”绘制,但旋转似乎无法围绕该点旋转。它太高了,右边似乎显示旋转是围绕图层中心而不是文本的中心。

谢谢,问问Rob。

我想我可能已经解决了这个问题:

void drawTextAtAngle (CGContextRef context, NSString *label, NSPoint pt, double angle)
{
   CGContextSaveGState (context);

   /*
    * Move the rotation point and rotate around
    * that point.
    */       
   CGContextTranslateCTM (context, pt.x, pt.y);
   CGContextRotateCTM (context, angle);

   /*
    * Now that 0,0 is at the point we want the text draw there
    */
   pt = NSMakePoint (0.0, 0.0);

   CGContextSelectFont (context, "Helvetica", 14.0, kCGEncodingMacRoman);
   CGContextShowTextAtPoint (context, pt.x, pt.y, [label UTF8String], [label length]);

   CGContextRestoreGState (context);
}

我现在需要锻炼多大的'标签',以便我可以集中精力,但这是以后的另一个问题。

0 个答案:

没有答案