Drawing rotated text with NSString drawInRect

前端 未结 5 1847
借酒劲吻你
借酒劲吻你 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:55

    Thank for this post, and Chris's answer, and Arkadiusz's answer at another post.

    Finally, I solve this problem by a UILabel subclass, named MyVerticalLabel, and make it draw vertical text.

    @implementation MyVerticalLabel
    
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect {
        // Drawing code
    
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGAffineTransform transform = CGAffineTransformMakeRotation(-M_PI_2);
        CGContextConcatCTM(context, transform);
        CGContextTranslateCTM(context, -rect.size.height, 0);
    
        // The drawing rect should be applied with transform to.
        CGRect newRect = CGRectApplyAffineTransform(rect, transform);
        newRect.origin = CGPointZero;
    
        NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
        textStyle.lineBreakMode = self.lineBreakMode;
        textStyle.alignment = self.textAlignment;
    
        // Apply current label attributes for drawing function.
        NSDictionary *attributeDict =
        @{
          NSFontAttributeName : self.font,
          NSForegroundColorAttributeName : self.textColor,
          NSParagraphStyleAttributeName : textStyle,
          };
        [self.text drawInRect:newRect withAttributes:attributeDict];
    }
    
    @end
    

提交回复
热议问题