本文介绍了如何获得UILabel(UITextView)自动调整字体大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自动调整后是否可以获得最终字体大小? (属性adjustsFontSizeToFitWidth设置为YES,文本字体大小正在缩小以适合标签)

Is it possible to get final font size, after autoadjusting? (property adjustsFontSizeToFitWidth set to YES, and text font size is being shrinked to fit into the label)

我在UILabel中继承drawTextInRect以在文本上放置渐变,但是渐变大小需要与字体大小相同。我无法获得调整后的字体大小...是否可能?

I am subclassing drawTextInRect in UILabel to put gradient on the text, but the gradient size needs to be the same, as the size of the font. I am not able to get proper size of the adjusted font...Is it even possible?

  //draw gradient

    CGContextSaveGState(myContext);
        CGGradientRef glossGradient;
        CGColorSpaceRef rgbColorspace;
        size_t num_locations = 2;
        CGFloat locations[2] = { 0.0, 1.0 };
        CGFloat components[8] = { 1, 1, 1, 0.25,  // BOTTOM color
            1, 1, 1, 0.12 }; // UPPER color

    //scale and translate so that text would not be rotated 180 deg wrong
        CGContextTranslateCTM(myContext, 0, rect.size.height);
        CGContextScaleCTM(myContext, 1.0, -1.0);

//create mask
        CGImageRef alphaMask = CGBitmapContextCreateImage(myContext);
        CGContextClipToMask(myContext, rect, alphaMask);

        rgbColorspace = CGColorSpaceCreateDeviceRGB();
        glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);

    //gradient should be sized to actual font size. THIS IS THE PROBLEM - EVEN IF FONT IS AUTO ADUJSTED, I AM GETTING THE SAME ORIGINAL FONT SIZE!!!

        CGFloat fontCapHeightHalf = (self.font.capHeight/2)+5;
            CGRect currentBounds = rect;
        CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds)-fontCapHeightHalf);
        CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds)+fontCapHeightHalf);

        CGContextDrawLinearGradient(myContext, glossGradient, topCenter, midCenter, 0);

        CGGradientRelease(glossGradient);
        CGColorSpaceRelease(rgbColorspace);
    CGContextRestoreGState(myContext);


推荐答案

你无法直接获得尺寸,但是你可以使用:

You can't get the size directly, but you can calculate it easily enough using these functions:

CGFloat actualFontSize;
[label.text sizeWithFont:label.font
             minFontSize:label.minimumFontSize
          actualFontSize:&actualFontSize
                forWidth:label.bounds.size.width
           lineBreakMode:label.lineBreakMode];

这篇关于如何获得UILabel(UITextView)自动调整字体大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 06:37