在Android中使用Path绘制箭头

时间:2014-10-11 06:58:22

标签: android view path

我在http://www.curious-creature.org/2013/12/21/android-recipe-4-path-tracing/

上阅读了这篇文章

尝试使用文章中提到的Path绘制箭头,但是使用以下代码,我得到了半箭头,我已经阅读了有关如何在android上绘制箭头的文章。这个问题更多的是“下面的代码有什么问题。”提前谢谢。

package com.example.linepractice;

import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PracticeLineView pl = new PracticeLineView(this);
        LayoutInflater mInflater = LayoutInflater.from(this);
        LinearLayout mainView = (LinearLayout) mInflater.inflate(R.layout.activity_main, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.setMargins(120, 120, 120, 120);
        pl.setLayoutParams(params);
        mainView.addView(pl);
        setContentView(mainView);
    }
}


package com.example.linepractice;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;

public class PracticeLineView extends View {
    private Paint mPaint;
    public PracticeLineView(Context context) {
        super(context);
        mPaint = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(getPaddingLeft(), getPaddingTop() - getPaddingBottom());
        canvas.drawPath(makeArrow(140,140), mPaint);
    }

    private static Path makeArrow(float length, float height) {
        Path p = new Path();
        p.moveTo(-2.0f, -height / 2.0f);
        p.lineTo(length, 0.0f);
        p.lineTo(-2.0f, height / 2.0f);
        p.lineTo(-2.0f, -height / 2.0f);
        p.close();
        return p;
    }
}

PIC: code result

1 个答案:

答案 0 :(得分:3)

private static Path makeArrow(float length, float height) {
    Path p = new Path();
    p.moveTo(-2.0f, 0.0f);
    p.lineTo(length, height / 2.0f);
    p.lineTo(-2.0f, height);
    p.lineTo(-2.0f, 0.0f);
    p.close();
    return p;
}