绘制的TextView不会出现

时间:2018-04-28 03:57:56

标签: android xamarin.android

我有这个类用于将文本绘制到画布上。当我绘制文字时,什么都没有出现。虽然可以绘制画布,因为其他一些代码工作正常。

我有什么遗失的东西吗?此外,最好也限制画布的可绘制区域的宽度和高度。

上下文来自与画布相同的视图。

public class GraphicsDroid
    {
        readonly Android.Graphics.Canvas canvas;
        readonly Context context;

        public GraphicsDroid(Android.Graphics.Canvas canvas, Context context)
        {
            this.canvas = canvas;
            this.context = context;
        }

        public void DrawText((Color?, Color) color, float fontSize, string text, float x, float y, float width, float height)
        {
            var textView = new TextView(context)
            {
                Text = text
            };

            textView.SetSingleLine(true);
            textView.Ellipsize = TruncateAt.End;
            textView.SetTextColor(color.Item2.ToAndroid());
            textView.TextSize = fontSize;
            textView.SetWidth((int) width);
            textView.SetHeight((int) height);

            if (color.Item1 is Color background)
            {
                textView.SetBackgroundColor(background.ToAndroid());
            }

            var saveCount = canvas.Save();

            try
            {
                canvas.Translate(x, y);

                textView.Draw(canvas);
            }
            finally
            {
                canvas.RestoreToCount(saveCount);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我将textview渲染为布局......

public void DrawText((Color?, Color) color, float fontSize, string text, float x, float y, float width, float height)
        {
            var layout = new LinearLayout(context);

            var textView = new TextView(context)
            {
                Text = text
            };

            textView.SetSingleLine(true);
            textView.Ellipsize = TruncateAt.End;
            textView.SetTextColor(color.Item2.ToAndroid());
            textView.TextSize = fontSize;
            textView.SetWidth((int) width);
            textView.SetHeight((int) height);

            if (color.Item1 is Color background)
            {
                textView.SetBackgroundColor(background.ToAndroid());
            }

            layout.AddView(textView);

            layout.Measure(canvas.Width, canvas.Height);
            layout.Layout(0, 0, canvas.Width, canvas.Height);

            var saveCount = canvas.Save();

            try
            {
                canvas.Translate(x, y);

                layout.Draw(canvas);
            }
            finally
            {
                canvas.RestoreToCount(saveCount);
            }
        }