Drawing rotated text with NSString drawInRect

前端 未结 5 1854
借酒劲吻你
借酒劲吻你 2020-11-29 04:09

I found this answer on how to draw rotated text with NSString drawInRect:, but I\'m not sure how it works since it only sort of works for me: https://discussions.apple.com/t

5条回答
  •  广开言路
    2020-11-29 04:44

    I think what's happening is that you're rotating the text to a location outside of the view because it rotates the context by pivoting on the origin.

    After your rotation you need to do a translation to move the context back into the view. In the example below, I rotate the context counterclockwise 90 degrees. Then I translate the tx of the context the distance of the height.

    - (void)drawRect:(CGRect)rect
    {
        CGContextRef context = UIGraphicsGetCurrentContext(); 
    
        CGContextSaveGState(context);
    
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
        // Create the gradient 
        CGColorRef startColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0].CGColor; 
        CGColorRef endColor = [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:1.0].CGColor;
        NSArray *colors = [NSArray arrayWithObjects:(id)startColor, (id)endColor, nil];
        CGFloat locations[] = { 0.0, 1.0 };
        CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef) colors, locations);
        CGContextDrawLinearGradient(context, gradient, CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y), CGPointMake(rect.origin.x + rect.size.width / 2, rect.origin.y + rect.size.height), 0);
    
        // Create text              
        CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor); 
        NSString *string = @"some test string";
        UIFont *font = [UIFont systemFontOfSize:16.0];
    
        // Rotate the context 90 degrees (convert to radians)
        CGAffineTransform transform1 = CGAffineTransformMakeRotation(-M_PI_2);
        CGContextConcatCTM(context, transform1); 
    
        // Move the context back into the view 
        CGContextTranslateCTM(context, -rect.size.height, 0);
    
        // Draw the string 
        [string drawInRect:rect withFont:font lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
    
        // Clean up 
        CGGradientRelease(gradient);
        CGColorSpaceRelease(colorSpace);
    
        CGContextRestoreGState(context);
    }
    

    Note that you can also get the size of how the string will be rendered, which can help in doing calculations for the alignment of the text.

        CGSize stringSize = [string sizeWithFont:font]; 
    

提交回复
热议问题