iOS - 在Quartz上垂直缩放文本

时间:2012-09-26 11:51:34

标签: iphone ios ipad quartz-graphics

我正在写一些石英背景文本。

我有一个500 x 200像素的盒子,我在里面写了一些文字。该框可以具有任何宽高比,但文本将始终以字体比例写入。我想要的是垂直缩放字体并保持水平刻度。

见图。第一个框代表我得到的东西,第二个框代表我想要的东西。

enter image description here

这就是我写它的方式......

CGRect rect = CGRectMake(0,0,500,200);
[myText drawInRect:rect
        withFont:aFont
        lineBreakMode:UILineBreakModeTailTruncation
        alignment:UITextAlignmentCenter];

有没有办法垂直缩放字体?

  

注意:由于这是在PDF环境中编写的,我不想这样做   将文本渲染到图像上下文并垂直缩放,因为我   不想失去决心。

感谢

1 个答案:

答案 0 :(得分:1)

  - (void) scaleTextVerticallyWithContext:(CGContextRef)myContext withRect:(CGRect)contextRect
{
    CGFloat w, h;
    w = contextRect.size.width;
    h = contextRect.size.height;

    CGAffineTransform myTextTransform;    
    CGContextSelectFont (myContext, "Helvetica-Bold", h/10, kCGEncodingMacRoman);
    CGContextSetCharacterSpacing (myContext, 10);
    CGContextSetTextDrawingMode (myContext, kCGTextFillStroke); 

    CGContextSetRGBFillColor (myContext, 0, 1, 0, .5);
    CGContextSetRGBStrokeColor (myContext, 0, 0, 1, 1);  

         /*  
          *  CGAffineTransformMakeScale ( CGFloat sx, CGFloat sy );
          *  sx: The factor by which to scale the x-axis of the coordinate system.
          *  sy: The factor by which to scale the y-axis of the coordinate system.  
          */

    myTextTransform = CGAffineTransformMakeScale(1,8);

    CGContextSetTextMatrix (myContext, myTextTransform);
    CGContextShowTextAtPoint (myContext, 40, 0, "Hello There", 9);
}

- (void)drawRect:(CGRect)rect{

    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect viewBounds = self.bounds;
    CGContextTranslateCTM(context, 0, viewBounds.size.height);
    CGContextScaleCTM(context, 1, -1);

    [self scaleTextVerticallyWithContext:context withRect:viewBounds];
}