首页 > 解决方案 > 动态添加点到画布中的路径

问题描述

我是 Android 新手,我正在学习如何在画布上绘图。如何向 Path 添加新点并动态绘制它们?现在我从 MainActivity 调用我的自定义视图类的函数 (setPoints()) 并将点传递给它,但路径没有被绘制。有人可以建议正确的方法或帮助我吗?我被困在这一点上。

public class RenderPointsMap extends View {

public int width;
public int height;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
Context context;
private Paint mPaint;
private float mX, mY;
private static final float TOLERANCE = 5;
Vector<PointF> temp = new Vector<>();
 PointF usethis  = new PointF();


public RenderPointsMap(Context c, AttributeSet attrs) {
    super(c, attrs);
    context = c;

    // we set a new Path
    mPath = new Path();

    // and we set a new Paint with the desired attributes
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setColor(Color.BLACK);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeWidth(2f);


}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    // your Canvas will draw onto the defined Bitmap
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
}

// override onDraw
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // draw the mPath with the mPaint on the canvas when onDraw
    mCanvas = canvas;
    canvas.drawPath(mPath, mPaint);
}

public void setPoints(Vector<PointF> points){
    mPath.moveTo(200, 200);
    for(int i=1;i<points.size();i++)
        mPath.lineTo(points.get(i).x, points.get(i).y);

    Toast.makeText(getContext(), "Points are set", Toast.LENGTH_SHORT).show();
}

}

标签: androidcanvasbitmapandroid-canvas

解决方案


推荐阅读