菜鸟教程小白 发表于 2022-12-11 19:32:11

ios - 使用objective-c/core图形的水平居中文本


                                            <p><p>我正在尝试使用 Core Graphics 使文本在 iPhone 屏幕上居中,我发现 <a href="https://stackoverflow.com/questions/48034940/draw-centered-text-using-core-graphics-mobile-device/" rel="noreferrer noopener nofollow">this code</a> .</p>

<pre><code>CGRect screenRect = [ bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
NSString * text = @&#34;text&#34;;
CGFloat minHeight = 40;
float widthIs = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, minHeight) options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName: }
context:nil].size.width;
CGContextSetFillColorWithColor(context, .CGColor);
];
</code></pre>

<p>但是为我自己尝试这段代码我无法真正让它工作。文本并没有真正集中在我的屏幕上,我不知道如何编辑代码来解决我的问题。</p>

<p>这是我得到的结果:</p>

<p> <img src="/image/F3A5B.jpg" alt="image"/> </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>这看起来基本正确:一些小的观察:</p>

<ol>
<li><p>我不指代 <code>UIScreen</code>,而只是指代呈现文本的 View 。例如。如果实际上在某些 <code>UIView</code> 子类实现中,您只需引用 <code>self.bounds.size</code>。</p></li>
<li><p>我会使用 <code>attributes</code> 再现,不仅可以获取边界矩形的大小,还可以获取 <code>drawAtPoint</code>。例如。使用 <code>drawAtPoint:withAttributes:</code> 而不是 <code>drawAtPoint:withFont:</code>。</p></li>
<li><p>字体颜色也应该是 <code>attributes</code> 字典的一部分。</p></li>
</ol>

<p>例如:</p>

<pre><code>CGSize viewSize = self.bounds.size;
NSString *text = @&#34;text&#34;;
CGFloat minHeight = 40;
NSDictionary *attributes = @{NSFontAttributeName: , NSForegroundColorAttributeName: };
CGSize textSize = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, minHeight)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:attributes
                                     context:nil].size;
;
</code></pre>

<p>如果执行此操作后它仍未居中,则需要确认要在其中呈现它的 <code>UIView</code> 的 <code>frame</code>,并确保它是你认为应该在的地方。您可以在调试器中运行应用程序,然后使用 View 调试器 <a href="/image/3VtiB.png" rel="noreferrer noopener nofollow"><img src="/image/3VtiB.png" alt="view debugger"/></a>确认 View 的位置。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 使用objective-c/core图形的水平居中文本,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48035494/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48035494/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 使用objective-c/core图形的水平居中文本