簡體   English   中英

畫布以動態油漆顏色繪制路徑

[英]Canvas draw path with dynamic paint color

我正在為Arduino電機護罩編寫Android應用程序(實際上是Nucleo板,但這並不重要),並且我將超聲波聲納傳感器測得的距離顯示為屏幕上的點。 在Arduino的每次更新中(我發送了一個帶有伺服角度和聲納距離(以厘米為單位)的數據包),我繪制了一個新的Point。 問題是,有時對於相同的伺服角度,我有許多聲納距離,如果我全部繪制它們,會變得混亂。

對於每個伺服角度(X軸),我只想繪制聲納距離(Y軸)的最新測量值。

這是具有相同伺服角度的許多點的圖。

這是我用來在視圖畫布上繪制所有傳入點的代碼: https : //github.com/dizcza/FunduMotoJoystick/blob/b224e80d59fe11c0252dce7f78aca995f67a7d65/app/src/main/java/de/kai_morich/fundu_moto_joystick/SonarView。

public class SonarView extends View {
    private static final int POINT_RADIUS = 10;
    private final Paint mPaint = new Paint();
    private final Path mPath = new Path();

    public SonarView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.BLACK);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawPath(mPath, mPaint);
    }

    public void drawCircle(float x, float y) {
        mPath.addCircle(x, y, POINT_RADIUS, Path.Direction.CW);
        invalidate();
    }

    public void clear() {
        mPath.reset();
    }
}

我之所以稱其為“具有動態繪畫顏色的畫布繪制路徑”,是因為如果我可以為路徑中每個添加的項目(圓形)顯式提供顏色,則每次都會繪制一個白色矩形以覆蓋每個新點下方的空間。

創建一個方法,將油漆對象返回為

public Paint getCustomPaint(int color){
     Paint paint = new Paint();
     paint.setStyle(Paint.Style.FILL); 
     paint.setColor(color);
     return paint;
}

並將其稱為canvas.drawPath(mPath, getCustomPaint(randomColor));

編輯:

根據您的要求,您需要維護一個ArrayList(在其頂部添加),如下所示:

private ArrayList<Point> mPointsList = new ArrayList<>();
private ArrayList<Point> mWhitePointsList = new ArrayList<>();
private final Path mWhitePath = new Path();

然后添加一個新方法,

private boolean isPointPresent(float x, float y) {
    Point lPoint = new Point((int)x, (int)y);
    boolean isFound = false;
    for (Point point : mPointsList){
        if(point.x == x){
            isFound = true;
            mPointsList.remove(point);
            mWhitePointsList.add(point);
        }
    }
    if(isFound) {
        mPointsList.add(lPoint);
        return true;
    }
    mPointsList.add(lPoint);
    return false;
}

同樣,在drawCircle方法中進行如下更改:

public void drawCircle(float x, float y) {
    if(isPointPresent(x, y)) {
        for(Point point : mWhitePointsList){
            mWhitePath.addCircle(point.x, point.y, POINT_RADIUS, Path.Direction.CW );
            mWhitePointsList.remove(point);
        }
    }
    mPath.addCircle(x, y, POINT_RADIUS, Path.Direction.CW);
    invalidate();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM