web-dev-qa-db-ja.com

UILabelで垂直テキストを描画する方法

現在、ラベルに縦書きの中国語のテキストを描画する作業をしています。漢字ではありますが、これが私が達成しようとしていることです:

Express

私は、各文字を描き、各文字を左に90度回転させ、アフィン変換を介してラベル全体を回転させ、最終的な結果を取得することを計画しています。しかし、それはひどく複雑に感じます。複雑なCoreGraphicsのマジックを使わずにテキストを描画する簡単な方法はありますか?

26
futureelite7

さて、あなたは以下のようにすることができます:

labelObject.numberOfLines = 0;
labelObject.lineBreakMode = NSLineBreakByCharWrapping;

そしてsetFrame with-height:100、width:20それは正常に動作します。

36
Simha.IC

できます

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 100)];
lbl.transform = CGAffineTransformMakeRotation((M_PI)/2);
21
Sanket Pandya

Simha.ICが提供する方法を試しましたが、私にはうまくいきませんでした。一部の文字は他の文字よりも細く、1行に2つ配置されます。例えば。

W
ai
ti
n
g

私の解決策は、各文字の後に\nを追加することにより、文字列自体を複数行のテキストに変換するメソッドを作成することでした。メソッドは次のとおりです。

- (NSString *)transformStringToVertical:(NSString *)originalString
{
    NSMutableString *mutableString = [NSMutableString stringWithString:originalString];
    NSRange stringRange = [mutableString rangeOfString:mutableString];

    for (int i = 1; i < stringRange.length*2 - 2; i+=2)
    {
        [mutableString insertString:@"\n" atIndex:i];
    }

    return mutableString;
}

次に、次のようにラベルを設定します。

label.text = [self transformStringToVertical:myString];
CGRect labelFrame = label.frame;
labelFrame.size.width  = label.font.pointSize;
labelFrame.size.height = label.font.lineHeight * myString.length;
label.frame = labelFrame;

楽しい!

11
AXE

ラベル全体(文字を含む)を回転したい場合は、次のようにします。

  1. まず、QuartzCoreライブラリをプロジェクトに追加します。
  2. ラベルを作成します。

    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 300.0, 30.0)];
    [label setText:@"Label Text"];
    
  3. ラベルを回転させます。

    [label setTransform:CGAffineTransformMakeRotation(-M_PI / 2)];
    

ラベルの配置方法によっては、アンカーポイントを設定する必要があります。これにより、回転が発生するポイントが設定されます。例えば:

    [label.layer setAnchorPoint:CGPointMake(0.0, 1.0)];
6
Jasper Blues

これは、UILabelをサブクラス化して、垂直テキストを描画するもう1つの方法です。しかし、それは質問が求めるものとは少し異なります。

Objective-C

@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);

    CGRect newRect = CGRectApplyAffineTransform(rect, transform);
    newRect.Origin = CGPointZero;

    NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    textStyle.lineBreakMode = self.lineBreakMode;
    textStyle.alignment = self.textAlignment;

    NSDictionary *attributeDict =
    @{
      NSFontAttributeName : self.font,
      NSForegroundColorAttributeName : self.textColor,
      NSParagraphStyleAttributeName : textStyle,
      };
    [self.text drawInRect:newRect withAttributes:attributeDict];
}
@end

サンプル画像は次のとおりです。

A sample image

Swift

ストーリーボードに貼って、結果を直接見ることができます。画像のように、そのフレームには垂直のテキストが含まれます。また、textAlignmentfontなどのテキスト属性もうまく機能します。

A vertical text example

@IBDesignable
class MyVerticalLabel: UILabel {

    override func drawRect(rect: CGRect) {
        guard let text = self.text else {
            return
        }

        // Drawing code
        let context = UIGraphicsGetCurrentContext()

        let transform = CGAffineTransformMakeRotation( CGFloat(-M_PI_2))
        CGContextConcatCTM(context, transform)
        CGContextTranslateCTM(context, -rect.size.height, 0)

        var newRect = CGRectApplyAffineTransform(rect, transform)
        newRect.Origin = CGPointZero

        let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
        textStyle.lineBreakMode = self.lineBreakMode
        textStyle.alignment = self.textAlignment

        let attributeDict: [String:AnyObject] = [
            NSFontAttributeName: self.font,
            NSForegroundColorAttributeName: self.textColor,
            NSParagraphStyleAttributeName: textStyle,
        ]

        let nsStr = text as NSString
        nsStr.drawInRect(newRect, withAttributes: attributeDict)
    }

}

スウィフト4

override func draw(_ rect: CGRect) {
    guard let text = self.text else {
        return
    }

    // Drawing code
    if let context = UIGraphicsGetCurrentContext() {
        let transform = CGAffineTransform( rotationAngle: CGFloat(-Double.pi/2))
        context.concatenate(transform)
        context.translateBy(x: -rect.size.height, y: 0)
        var newRect = rect.applying(transform)
        newRect.Origin = CGPoint.zero

        let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
        textStyle.lineBreakMode = self.lineBreakMode
        textStyle.alignment = self.textAlignment

        let attributeDict: [NSAttributedStringKey: AnyObject] = [NSAttributedStringKey.font: self.font, NSAttributedStringKey.foregroundColor: self.textColor, NSAttributedStringKey.paragraphStyle: textStyle]

        let nsStr = text as NSString
        nsStr.draw(in: newRect, withAttributes: attributeDict)
    }
}
5
AechoLiu