如何使用具有不同笔触宽度值的箭头绘制线条

时间:2017-08-23 04:13:35

标签: xamarin xamarin.android

当我尝试增加箭头笔划宽度时,我画了箭头,它看起来很奇怪。两条线重叠,厚度适用于中心。有没有其他方法可以向外应用strokewidth。

我在下面提到了画一个箭头的链接, How do I draw an arrowhead (in Android)?

public class Arrow: View
{
    float x0 = 300, y0 = 1000, x1 = 600, y1 = 200;
    internal static int DENSITY = -1;

    public Arrow(Context con):base(con)
    {
        DENSITY = (int)con.Resources.DisplayMetrics.Density;
    }

    protected override void OnDraw(Canvas canvas)
    {
        Paint paint = new Paint();
        paint.StrokeWidth = 10 * Arrow.DENSITY;
        float angle, anglerad, radius, lineangle;
        radius = 45;
        angle = 45;

        //calculate line angles
        anglerad = (float)(Math.Pi * angle / 180.0f);
        lineangle = (float)(Math.Atan2(y1 - y0, x1 - x0));
        Path mArrow = new Android.Graphics.Path();


        mArrow.MoveTo(x1, y1);
        var a1 = (float)(x1 - radius * Math.Cos(lineangle - (anglerad / 2.0)));
        var a2 = (float)(y1 - radius * Math.Sin(lineangle - (anglerad / 2.0)));
        mArrow.LineTo(a1, a2);
        mArrow.MoveTo(a1, a2);
        mArrow.MoveTo(x1, y1);
        var a3 = (float)(x1 - radius * Math.Cos(lineangle + (anglerad / 2.0)));
        var a4 = (float)(y1 - radius * Math.Sin(lineangle + (anglerad / 2.0)));
        mArrow.LineTo(a3, a4);

        paint.AntiAlias = true;
        paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
        canvas.DrawPath(mArrow, paint);
        canvas.DrawLine(x0, y0, x1, y1, paint);

        base.OnDraw(canvas);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用QuadTo替换此处的LineTo,因为此api会从最后一个点添加二次贝塞尔曲线,接近控制点(x1,y1),并以(x2,y2)结束)。注意线的起点和最后一点。

所以你可以替换你的代码:

mArrow.MoveTo(x1, y1);
var a1 = (float)(x1 - radius * Math.Cos(lineangle - (anglerad / 2.0)));
var a2 = (float)(y1 - radius * Math.Sin(lineangle - (anglerad / 2.0)));
mArrow.LineTo(a1, a2);
mArrow.MoveTo(a1, a2);
mArrow.MoveTo(x1, y1);
var a3 = (float)(x1 - radius * Math.Cos(lineangle + (anglerad / 2.0)));
var a4 = (float)(y1 - radius * Math.Sin(lineangle + (anglerad / 2.0)));
mArrow.LineTo(a3, a4);

要:

var a1 = (float)(x1 - radius * Java.Lang.Math.Cos(lineangle - (anglerad / 2.0)));
var a2 = (float)(y1 - radius * Java.Lang.Math.Sin(lineangle - (anglerad / 2.0)));
mArrow.MoveTo(a1, a2);
mArrow.QuadTo(a1, a2, x1, y1);
var a3 = (float)(x1 - radius * Java.Lang.Math.Cos(lineangle + (anglerad / 2.0)));
var a4 = (float)(y1 - radius * Java.Lang.Math.Sin(lineangle + (anglerad / 2.0)));
mArrow.QuadTo(x1, y1, a3, a4);

我更改了paint.Color以便在我身边说清楚:

enter image description here