繁体   English   中英

如何在 UILabel 中绘制垂直文本

[英]How to draw vertical text in UILabel

我目前正在研究在标签中绘制垂直中文文本。 这是我想要实现的目标,尽管使用汉字:

特快列车

我一直在计划绘制每个字符,将每个字符向左旋转 90 度,然后通过仿射变换旋转整个标签以获得最终结果。 然而,这感觉非常复杂。 有没有更简单的方法来绘制文本而没有我缺少的复杂 CoreGraphics 魔法?

好吧,你可以这样做:

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

和 setFrame with -- height:100, width:20 它会正常工作..

有用

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

尝试了 Simha.IC 提供的方法,但对我来说效果不佳。 有些字符比其他字符更薄,并在一条线上放置两个。 例如

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;

享受!

如果你想旋转整个标签(包括字符),你可以这样做:

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

这是另一种绘制垂直文本的方法,通过UILabel 但这与问题想要的有些不同。

目标-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

示例图像如下:

示例图像

迅速

可以放到storyboard上,直接看结果。 像图像一样,它的框架将包含垂直文本。 文本属性,如textAlignmentfont ,也能很好地工作。

竖排文本示例

@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)
    }
}
import UIKit

class VerticalLabel : UILabel {
    
    private var _text : String? = nil
    
    override var text : String? {
        get {
            return _text
        }
        set {
            self.numberOfLines = 0
            self.textAlignment = .center
            self.lineBreakMode = .byWordWrapping
            _text = newValue
            if let t = _text {
                var s = ""
                for c in t {
                    s += "\(c)\n"
                }
                super.text = s
            }
        }
    }
    
}

斯威夫特 5

使用 CGAffineTransform 更简单的方法

import UIKit
class ViewController: UIViewController {

@IBOutlet weak var verticalText: UILabel

    override func viewDidLoad() {

        verticalText.transform = CGAffineTransform(rotationAngle:CGFloat.pi/2)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM