如何在 Xamarin iOS 中绘制文本?

2024-04-14

我想在给定点(x,y)处绘制文本Draw自定义的方法View.

我已关注这个样本 https://developer.xamarin.com/recipes/ios/graphics_and_drawing/core_text/draw_unicode_text_with_coretext/来自 Xamarin 网站。

这是我创建的视图:

public class MyView : UIView
{
    public override void Draw(CGRect rect)
    {
        using (var context = UIGraphics.GetCurrentContext())
        {
            DrawText(context, "hello", 20, new CGPoint(0, 0));
            DrawText(context, "how are you", 20, new CGPoint(0, 40));
        }
    }

    private void DrawText(CGContext context, string text, int textHeight, CGPoint point)
    {
        var x = point.X;
        var y = point.Y + textHeight;

        context.TranslateCTM(x, y);

        context.ScaleCTM(1, -1);
        context.SetFillColor(UIColor.Red.CGColor);

        var attributedString = new NSAttributedString(text,
            new CTStringAttributes
            {
                ForegroundColorFromContext = true,
                Font = new CTFont("Arial", 16)
            });

        using (var textLine = new CTLine(attributedString))
        {
            textLine.Draw(context);
        }
    }
}

问题是DrawText method 只能正常工作一次。第一次调用它时,文本被绘制,但是它不适用于连续调用(它不绘制任何内容,或者它绘制的内容不可见)。

我究竟做错了什么?


因此,您的代码有两个基本问题。

  • 你正在执行一个ScaleCTM and a TranslateCTM每次你打电话DrawText
  • 当你CTLine.Draw,“光标”移动到该文本的末尾。

所以,打电话ScaleCTM翻转整个内容,以便文本从左到右绘制,然后调用DrawText并翻译到您想要绘制文本的位置,然后翻译回来到您开始的地方,以便下次您在同一点。

绘制覆盖示例:

public override void Draw(CGRect rect)
{
    var context = UIGraphics.GetCurrentContext();
    context.ScaleCTM(1, -1); // you flipped the context, now you must use negative Y values to draw "into" the view

    var textHeight = new CTFont("Arial", 16).CapHeightMetric; // lets use the actaul height of the font captials.

    DrawText(context, "Hello", textHeight, 0, 0);
    DrawText(context, "How are you?", textHeight, 0, 20);
    DrawText(context, "Sincerely,", textHeight, 0, 40);
    DrawText(context, "StackOverflow,", textHeight, 0, 60);
}

void DrawText(CGContext context, string text, nfloat textHeight, nfloat x, nfloat y)
{
    context.TranslateCTM(-x, -(y + textHeight));
    context.SetFillColor(UIColor.Red.CGColor);

    var attributedString = new NSAttributedString(text,
        new CTStringAttributes
        {
            ForegroundColorFromContext = true,
            Font = new CTFont("Arial", 16)
        });

    CGRect sizeOfText;
    using (var textLine = new CTLine(attributedString))
    {
        textLine.Draw(context);
        sizeOfText = textLine.GetBounds(CTLineBoundsOptions.UseOpticalBounds);
    }
    // Reset the origin back to where is was
    context.TranslateCTM(x - sizeOfText.Width, y + sizeOfText.Height); 
}

结果是:

使用 NSMutableParagraphStyle 和 NSString.DrawString

var context = UIGraphics.GetCurrentContext();
CGRect textRect = new CGRect(0.0f, 0.0f, 200.0f, 100.0f);
{
    var textContent = "Hello\nHow are you?\nSincerely,\nStackOverflow";
    UIColor.Red.SetFill();
    var textStyle = new NSMutableParagraphStyle ();
    textStyle.Alignment = UITextAlignment.Left;

    var textFontAttributes = new UIStringAttributes () {Font = UIFont.FromName("ArialMT", 16.0f), ForegroundColor = UIColor.Red, ParagraphStyle = textStyle};
    var textTextHeight = new NSString(textContent).GetBoundingRect(new CGSize(textRect.Width, nfloat.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin, textFontAttributes, null).Height;
    context.SaveState();
    context.ClipToRect(textRect);
    new NSString(textContent).DrawString(new CGRect(textRect.GetMinX(), textRect.GetMinY() + (textRect.Height - textTextHeight) / 2.0f, textRect.Width, textTextHeight), UIFont.FromName("ArialMT", 16.0f), UILineBreakMode.WordWrap, UITextAlignment.Left);
    context.RestoreState();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Xamarin iOS 中绘制文本? 的相关文章

随机推荐

  • 如何使用 SQLiteOpenHelper 与 sd 卡上的数据库?

    根据这里和网络扩展应用程序中的各种答案及其继承的方法 getDatabasePath 将允许设置从标准内部存储器位置到插入的更大尺寸的 SD 卡的数据库存储路径 这对我不起作用 建议的构造仍然使用内存上的数据库 事实上 SQLiteOpen
  • 推送通知中不播放声音

    我使用的是 iOS 7 我的推送通知不播放声音 Strangely I found there is no setting for sound in the Preference gt Notification Center for my
  • 使用 Javascript 函数更改 onclick 操作

    我有一个按钮
  • 创建额外的 D3.js 符号

    D3 已经具有很多功能symbols https github com mbostock d3 wiki SVG Shapes wiki symbol 但我想添加一个自定义的 这样我就可以打电话d3 svg symbol type cust
  • Android底部导航栏项目背景颜色在选择fragment时发生变化

    我希望我的底部导航栏在按下时改变背景颜色 仅选定区域 就像下面的链接一样 http uupload ir files nq3k tab bar jpg http uupload ir files nq3k tab bar jpg 这是我的选
  • nifi invokehttp post复杂的json

    我尝试在 Apache NiFi 中使用 InvokeHttpProcessor 来执行具有复杂 JSON 正文的 POST 请求 因此本教程 http www tomaszezula com 2016 10 30 nifi and htt
  • PostgreSQL 中是否有可用的多值字段类型?

    我想知道是否可以在 PostgreSQL 的一个字段中存储多个值 我有一张桌子叫Token与列id text and category category是一个多值字段 是否有必要为其创建一个单独的表 或者有没有办法将其存储在Token ta
  • java.lang.NoSuchMethodError:没有静态方法 getDrawable(Landroid/content/Context;I)

    正在将 Socialize SDK 集成到我的应用程序中 我还将 Android Studio 更新到了 2 3 3 我的 Activity 的 super onCreate savedInstanceState 给了我一个错误 这里也提出
  • malloc(0) 的行为

    int main char p p char malloc sizeof char 0 printf Hello Enter the data without spaces n scanf s p printf The entered st
  • 如何在 Java 中定义重复的枚举常量?

    我想定义一个具有两个 值 相同的常量的枚举类型 我将这两个常量称为重复项 考虑以下示例 我想要定义一个浏览器类型列表 并且想要同时拥有文字 IE 和 InternetExplorer 如下所示 enum Browser CHROME chr
  • 关闭SKScene后,内存仍然居高不下

    我使用dispatch onceNSObject创建数据指针 因此 当主视图控制器出现时 所有游戏资源指针都会被创建 为了玩游戏 用户点击UIButton对应于某个特定级别UI视图控制器 让我称之为 LevelSelectionContro
  • AXML 和 XAML 之间的区别?

    我是 Visual Studio Xamarin 跨平台移动开发的新手 我一直在搜索 AXML 但我找不到任何设计和应用 MVC 方法的教程 实际上我对此有很多疑问 但我先把这 3 留在这里 他们有什么区别 xaml设计可以应用在axml中
  • 使用 psycopg cur.execute 创建 postgres 模式

    我的 python 应用程序允许用户创建其命名模式 我需要一种方法来保护应用程序免受 SQL 注入 要执行的SQL读取 CREATE SCHEMA schema name AUTHORIZATION user name psycopg 文档
  • PHP 正则表达式生成器

    我现在已经获得了满足以下所需条件的有效正则表达式字符串 一行 php 就绪正则表达式 包含许多关键字和关键术语 并且至少匹配其中一个 例如 关键术语 apple banana strawberry pear cake 现在 如果找到任何这些
  • git、mercurial、bazaar 源代码库的可理解性

    我想阅读一种流行的版本控制工具的源代码 以了解版本控制的工作原理 我想读一本最具可读性的书 我不知道对此有什么客观 定量的衡量标准 所以本着WTF 分钟漫画 http www osnews com story 19266 WTFs m 想请
  • 内容提供商中 Android 投影图的用途是什么?

    我正在查看 Android 记事本应用程序示例代码
  • Firefox Web 扩展“无法访问死对象”错误

    我很难找到这个问题的最新答案 并且经常没有时间在这里回答问题 所以我想我会发布这个 这样我就可以回答我自己的问题 因为我找到了解决方案 我正在为 Chrome 和 Firefox 制作一个 Web 扩展 Firefox 有一个问题 当我从选
  • 跨浏览器选项卡共享 websocket?

    我们希望每个浏览器都有一个套接字 而不是浏览器中的每个选项卡都有一个套接字 我们怎样才能实现它呢 我读到了有关共享网络工作者的文章 这很有前途 对此的参考也值得赞赏 不幸的是 据我所知 共享网络工作者尚未被 Mozilla 或 Intern
  • 在非托管 CDI Bean 中引用 CDI Bean

    是否可以在使用创建的类中获取 CDI bean 的实例new关键词 我们目前正在对旧应用程序进行一些增强 并且我们总是会得到上下文不活跃异常 http docs jboss org cdi api 1 0 javax enterprise
  • 如何在 Xamarin iOS 中绘制文本?

    我想在给定点 x y 处绘制文本Draw自定义的方法View 我已关注这个样本 https developer xamarin com recipes ios graphics and drawing core text draw unic