0

我正在将文本写入从 iDevice 的相机拍摄或从照片库中选择的图像上,但我需要根据图像的宽度/高度缩放字体大小。这是我当前的代码: UIGraphicsBeginImageContext(img.size);

CGRect aRectangle = CGRectMake(0,0, img.size.width, img.size.height);
[img drawInRect:aRectangle];

[[UIColor whiteColor] set];           // set text color
NSInteger fontSize = 45;
UIFont *font = [UIFont systemFontOfSize:fontSize];// set text font

[ text drawInRect : aRectangle                      // render the text
         withFont : font
    lineBreakMode : UILineBreakModeTailTruncation  // clip overflow from end of last line
        alignment : UITextAlignmentCenter ];

UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext();   // extract the image
UIGraphicsEndImageContext();     // clean  up the context.
return theImage;</i>
4

1 回答 1

0

你想要这样的东西。它会创建一个图像大小一半的矩形,然后使用二进制搜索放大您想要的字体大小。

//---- initial data
CGSize szMax = CGSizeMake(<imgWidth> / 2, <imgHeight> / 2);
CGFloat fMin = 2;      //-- the smallest size font we want
CGFloat fMax = 100;    //-- the largest size font we want
CGFloat fMid;          //-- the middle of min and max

while ((fMax - fMin) >= 1.0)    //-- repeat until the sizes converge
{
    fMid = (fMin + fMax) / 2.0;    //-- compute mid-point

    UIFont *pfnt = [UIFont systemFontOfSize: fMid];    //-- create middle-sized font

    //---- compute the size of the text using the mid-sized font
    CGSize szStr = [pStr sizeWithFont: pfnt constrainedToSize: szMax lineBreakMode: UILineBreakModeWordWrap];

    if (szStr.height > szMax.height)
        fMax = fMid;                //-- text too tall, set max to mid-point
    else               
        fMin = fMid;                //-- text too short, set min to mid-point
}
//---- 'fMid' is the size you want.
于 2012-09-20T02:54:31.567 回答