我正在将文字写入从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>
答案 0 :(得分: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.