【问题标题】:Scale NSString Font to UIImage Size将 NSString 字体缩放为 UIImage 大小
【发布时间】:2012-09-20 11:25:24
【问题描述】:

我正在将文本写入从 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>

【问题讨论】:

  • 您希望文本是单行还是多行?
  • 加入 fontScaling 聊天室。
  • @Kent 我收到这条消息:您必须在 Stack Overflow 上拥有 20 名声望才能在此处交谈。请参阅常见问题解答。我还是个新成员。
  • 啊。真可惜。所以更多的问题。您希望文本是图像的全高还是有其他限制?
  • @Kent 对于这部分文本,我希望它就像图像的中心标题一样。就像尺寸为 960x750 的图像一样,我会将字体大小设置为 45,所以它正好在中间并且足够大,可以看到,但问题是我不能让字体大小始终为 45,因为图像的大小变化。

标签: xcode nsstring uiimage font-size autoresize


【解决方案1】:

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

//---- 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.

【讨论】:

  • 我正在尝试实现代码,但我有点困惑它是如何工作的,你能解释一下吗?我是 Objective C 的新手,过去 7 年多来我一直在使用 .NET 和 C# 进行编程,所以调整有点复杂。
  • 一个问题@Kent,我不确定将我的 UIFont 设置为什么,我尝试了 fMid 和 fMin,但文本覆盖了整个图像。
  • 查看最后一条评论。在循环结束时, fMid 应该是您想要的大小。添加 NSLog 语句以查看每个循环中 fMin、fMax 和 szStr 的值。你在 Atl 吗?
  • 哇,谢谢!这有很大帮助。 :) 我遇到了一些问题,我将 和 设置为 img.size.width 和 img.size.height,这会导致文本覆盖整个图像吗?另外我不确定 pStr 和 szMaxWidth 是什么。我用我的 NSString 替换了 pStr,但我不确定它是否修复了很多。
  • 你在 Atl 吗?请注意,我的代码将 szMax 设置为 &lt;imgHeight&gt; / 2。 pStr 是你的字符串。
猜你喜欢
  • 2023-03-22
  • 2021-08-22
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多