简体   繁体   English

如何计算 CATextLayer 字符串的边界框?

[英]How to calculate the bounding box of a CATextLayer's string?

At first sight my question looks really simple, but it seems that I really can't find solution.乍一看,我的问题看起来很简单,但似乎我真的找不到解决方案。 Here is what it is: I want to calculate the bounding box of a CATextLayer's string.它是这样的:我想计算 CATextLayer 字符串的边界框。 Here is what I do:这是我所做的:

CATextLayer *textLayer = [CATextLayer layer];
textLayer.frame = CGRectMake(80, 0.0f, 36.0f, 18.0f);
textLayer.string = @"12";
textLayer.fontSize = [UIFont systemFontSize];
textLayer.foregroundColor = [UIColor whiteColor].CGColor;

NSLog(@"(width,height)=(%f,%f)",
[textLayer.string sizeWithFont:textLayer.font].width,
[textLayer.string sizeWithFont:textLayer.font].height);

The problem is that the output is always : (width,height) = (8.000000,0.000000)问题是输出总是:(width,height) = (8.000000,0.000000)

As of iOS 7, use NSString 's boundingRectWithSize:options:attributes:context .从 iOS 7 开始,使用NSStringboundingRectWithSize:options:attributes:context sizeWithFont:constrainedToSize:lineBreakMode: is now deprecated. sizeWithFont:constrainedToSize:lineBreakMode:现在已弃用。

CGRect rect = [textLayer.string boundingRectWithSize:textLayer.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:nil context:nil];
CGSize size = CGSizeMake(ceilf(rect.size.width), ceilf(rect.size.height));

Use sizeWithFont:constrainedToSize:lineBreakMode:使用sizeWithFont:constrainedToSize:lineBreakMode:

[someString sizeWithFont:yourFont
       constrainedToSize:CGSizeMake(maxWidthYouSpecify, CGFLOAT_MAX)
           lineBreakMode:UILineBreakModeWordWrap];

//use below function for dynamic CATextLayer //将下面的函数用于动态 CATextLayer

func DynamicLableWidth(reason:NSString,cpT:CGPoint,width:CGFloat,reasonLayer:CATextLayer)
{

    //Dynamic CATextLayer with boundingRect
    let font = UIFont(name: "Arial", size: 20)!
    let attributes: [NSString : AnyObject] = [NSFontAttributeName: font]

    var rect:CGRect = reason.boundingRectWithSize(reasonLayer.frame.size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)

    var size:CGSize = CGSizeMake(rect.size.width, rect.size.height);
    if cpT.x+20+ceil(size.width)+20>width
    {
        reasonLayer.frame = CGRectMake(cpT.x-20-ceil(size.width)+20,  cpT.y-15, ceil(size.width)+20, 20)
    }
    else
    {
        reasonLayer.frame = CGRectMake(cpT.x+20,  cpT.y-15, rect.size.width+20, 20)
    }
}

This should do the trick preferredFrameSize from CATextLayer .这应该可以完成CATextLayer preferredFrameSize CATextLayer Code can go as follow:代码可以如下:

func createSampleLabel(coordinate origin: CGPoint) {
   let textLayer = CATextLayer()
   textLayer.string = "some string \n with line breaks and long values...."
   textLayer.frame = .init(origin: origin, size: textLayer.preferredFrameSize())
}

在此处输入图片说明

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

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