Search code examples
iphoneiosipadquartz-graphics

iOS - scaling text vertically on Quartz


I am writing some text to a quartz context.

I have a box of 500 x 200 pixels and I am writing some text inside. The box can have any aspect ratio but the text will always write with the font proportions as it is. What I want is to scale the font vertically and keep the horizontal scale.

See the picture. The first box represents what I am getting, the second one, what I want.

enter image description here

this is how I am writing it...

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

is there a way to scale the font vertically?

NOTE: as this is being written in a PDF context, I don't want to render the text to a image context and scale it vertically, because I don't want to lose resolution.

thanks


Solution

  •   - (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];
    }