我们可以画一个使用 Path 对象的圆吗? [在参数中,如 drawPath()]

Can we draw a circle that uses Path object? [in arguments, like drawPath()]

我输入了一个利用 Canvas.

的程序

它提供了一个弹出菜单,其中提供了 3 个绘图工具作为选项:

  1. 在屏幕上划线时画线

  2. 根据屏幕上的起点和终点画线

  3. 画一个圆

此外还有如下选项:

  1. 清除

  2. 撤消

在行上执行撤消时,完全没有问题,因为两者都是基于路径的。 (使用 List<Path>)。 但是这里开始了问题。圆是使用 Point 对象绘制的。所以问题是:

  1. 我无法Android区分 - 画线和圆的顺序。 例如:我画了 5 条线,然后画了 5 个圆(或 或者)。目前没有情报可以追踪他们 绘图顺序。因此撤消 canvas 绘制的直线和圆圈 一起导致混乱。
  2. 当前代码(尚未深入思考)需要点击 2 次才能撤消圆圈,而不是 1 次。

下面共享的代码(很复杂)。我尝试为每个绘图工具(直线、圆)指定一个 class - 它起作用了 - 除了 - 它没有在 Canvas 上绘制任何东西。于是,全部打包1class回来了。

代码:

package com.example.orbit_.undofortouch;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {

    Button b1, b2, b3;
    PopupMenu popup;
    int dtool;
    boolean touch,circle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout2);
        final DrawPanel dp = new DrawPanel(this);
        linearLayout.addView(dp);

        b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dp.Clear();
            }
        });

        b2 = (Button) findViewById(R.id.button2);
        b2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dp.Undo();
            }
        });

        b3 = (Button) findViewById(R.id.button3);
        b3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                popup = new PopupMenu(MainActivity.this, v);
                popup.getMenuInflater().inflate(R.menu.menu_main, popup.getMenu());

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.touch:
                                dtool = 1;
                                break;
                            case R.id.line:
                                dtool = 2;
                                break;
                            case R.id.circle:
                                dtool = 3;
                                break;
                        }

                        Log.v("EDITL:", "Drawtool:".concat(String.valueOf(item.getTitle())));

                        Toast.makeText(MainActivity.this,"Clicked popup menu item " + item.getTitle(),Toast.LENGTH_SHORT).show();
                        return true;
                    }

                });
                popup.show();
            }
        });

   }




class DrawPanel extends View implements View.OnTouchListener {

    Bitmap bmp;

    Canvas canvas;
    List<Path> paths, undone;
    List<Point> circlePoints,removeCircles;
    Paint paint;
    Path path;
    Point point;

    public DrawPanel(Context context, AttributeSet attributeSet, int defStyle) {
        super(context, attributeSet, defStyle);
    }

    public DrawPanel(Context context) {
        super(context);
        paint = new Paint();
        path = new Path();
        paths = new ArrayList<>();
        undone = new ArrayList<>();
        circlePoints = new ArrayList<>();
        removeCircles = new ArrayList<>();

        canvas = new Canvas();

        this.setOnTouchListener(this);

        paint.setStrokeWidth(3);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setDither(true);
        paint.setAntiAlias(true);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeJoin(Paint.Join.ROUND);



        bmp = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.desert);
        touch=false;
        circle=false;

    }

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


    @Override
    protected void onDraw(Canvas canvas) {

        for (Path p : paths)
            canvas.drawPath(p, paint);

        if (touch)
            canvas.drawPath(path, paint);
        touch = false;
        Log.v("Inside onDraw","Circle is".concat(String.valueOf(circle)));

            for (Point p : circlePoints)
                canvas.drawCircle(p.x, p.y, 5, paint);


    }


    float mX, mY,mx,my;
    final float TOUCH_TOLERANCE = 0;



    private void touch_start(float x, float y) {
        undone.clear();
        Log.v("ONTOUCH:", "Inside DOWN".concat("DOWN-X---:").concat(String.valueOf(x)).concat("**DOWN-Y---:").concat(String.valueOf(y)));
        path.reset();
        path.moveTo(x, y);
        mX = x;
        mY = y;
        mx = x;
        my = y;
    }

    private void touch_up() {
        paths.add(path);
        path = new Path();
    }

    private void touch_move(float x, float y) {
        path.moveTo(mX, mY);
        Log.v("ONTOUCH:", "Inside MOVE".concat("mX:").concat(String.valueOf(mX)).concat("mY:").concat(String.valueOf(mY)));
        Log.v("ONTOUCH:", "Inside MOVE".concat("MOVE-X---:").concat(String.valueOf(x)).concat("**MOVE-Y---:").concat(String.valueOf(y)));
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }

        path.lineTo(mX, mY);

        Log.v("MOVE:", " PATH ADDED & New Created");


    }




    @Override
    public boolean onTouch(View v, MotionEvent event) {

        float x = event.getX();
        float y = event.getY();

        switch (dtool) {

            case 1:
                touch=true;
                Touch(v, event, x, y);
                break;

            case 2:
                Line(v,event,x,y);
                break;

            case 3:
                Circle(v,event,x,y);
                break;

        }
        Log.v("ONTOUCH:", "OUTSIDE CASE");
        return true;
    }

    public void Line(View v, MotionEvent event, float x, float y) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;

            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;

            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
        }
    }

    public void Touch(View v, MotionEvent event, float x, float y) {
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                canvas.drawPath(path, paint);
                break;

            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                canvas.drawPath(path, paint);
                break;

            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();

                break;
        }
    }

    public void Circle(View v, MotionEvent event, float x, float y)
    {   point = new Point();
        point.x = (int)x;
        point.y = (int)y;
        path.moveTo(x,y);
        circle=true;
       if(event.getAction()==MotionEvent.ACTION_DOWN) {

           circlePoints.add(new Point(Math.round(point.x), Math.round(point.y)));
           invalidate();
           Log.v("Circle", "Inside Circle");
           circlePoints.add(point);
            paths.add(path);
           
       }
    }

    public void Clear() {
        paths.clear(); //Needs to be experimented
        path.reset();
        invalidate();
    }

    public void Undo() {
        if (paths.size() > 0) {
            undone.add(paths.remove(paths.size() - 1));
            invalidate();
        }
        else if(circlePoints.size()>0)
        {
            removeCircles.add(circlePoints.remove(circlePoints.size()-1));
            invalidate();
        }
    }
  }
}

XML布局代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_weight="0"
        android:layout_gravity="top">


    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Undo"
        android:id="@+id/button2"
        android:layout_gravity="right"
        android:layout_marginTop="-50dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear"
        android:layout_gravity="center_vertical|bottom"
        android:layout_marginTop="-50dp"
        android:enabled="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tools"
        android:id="@+id/button3"
        android:layout_gravity="center_horizontal"
        android:layout_weight="0"
        android:layout_marginTop="-50dp" />

</LinearLayout>

XML 主菜单代码:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">

    <item
        android:id="@+id/touch"
        android:title="Touch"/>
    <item
        android:id="@+id/circle"
        android:title="Circle"/>
    <item
        android:id="@+id/line"
        android:title="Line"/>



</menu>

棒棒糖+

把圆圈也做成路径就好了。你可以做一个 360 度的圆弧,那就是一个圆。撕掉所有其他用于处理圆圈的代码作为不同的野兽。

Path path = new Path();
path.addArc(0,0,50,50,0,360);
Path.addCircle(float x,float y,float radius, Path.Direction)

这个简单的代码完成了这件事。因为添加圆的点将包含在 Path 对象中。 paths.addPath(path) 只是将其添加到之前的路径列表(绘制的线条)中。

因此撤消也变得简单自然。因此解决方案。

感谢@pskink 提供原始解决方案。

P.S: 今天我意识到,从一个未完成的项目中休息并不是一个好的做法,但在某种程度上有时对某些人来说是这样,因为你不熟悉,现在可以正常思考了这是你以前做不到的。

完整答案:

  private Path thumbPath = new Path();


  private void updatePath() {
        float centerX = getWidth()/2.0f;
        float centerY = getHeight()/2.0f;

        thumbPath.reset();
        thumbPath.addCircle(centerX, centerY , thumbRadius-borderThickness , Path.Direction.CW);
        thumbPath.close();

    }

  @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(thumbPath, thumbPaint);
    }

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

我认为它可能对某些人也有帮助,所以我想为此提出另一种解决方案

我更喜欢自己动手:

publiv void drawCircle(float center_x, float center_y, float radius, double omega) {
    /*
    Circle with center(a, b)
        
    equation of circle :
    (x - a)^2 + (y - b)^2 = radius^2
        
    x = (+- sqrt( radius^2 - (y - b)^2 )) + a
    y = (+- sqrt( radius^2 - (x - a)^2 )) + b
        
    omega -- angular velocity = angular displacement / time
    describes how many rotation(s) in 1s : ? rad / s
    OR
    use how much time for 1 revolution : 2pi rad / ? s
    */
    Path path = new Path();
    // path.addCircle(x, y, radius, Path.Direction.CCW);
    path.moveTo(center_x + radius, center_y);
        
    for (float i = center_x + radius; i >= center_x - radius; --i) {  // center-x +- radius
        // x : right -> left
        // y : anti-clockwise
        path.lineTo(i, (long) - Math.sqrt(radius * radius - (i - center_x) * (i - center_x)) + center_y);
    }
    
    for (float i = center_x - radius; i <= center_x + radius; ++i) {  // center-x +- radius
        // x : left -> right
        // y : anti-clockwise
        path.lineTo(i, (long) Math.sqrt(radius * radius - (i - center_x) * (i - center_x)) + center_y);
    }

    // and the draw in canvas with path part
}

然后 path 将从右(0 弧度)向上移动(anti-clockwise)(到 pi/2 弧度,pi 弧度,3pi/2 弧度, 2pi rad at the end ) 并以圆心 (center_x, center_y) 和半径 radius

完成圆的路径

// 这里可以忽略变量omega 哈哈

希望对您有所帮助