Android Canvas Draw by finger

后端 未结 2 1381
無奈伤痛
無奈伤痛 2020-12-29 16:20

On a project I’m working on at my current job, I’ve come across some really pernicious problems where there is either

no good information available or
the go         


        
2条回答
  •  囚心锁ツ
    2020-12-29 16:53

    1. Create a class that extends View and paste below code.

    public class CustomClass extends View {
    
      private Paint paint = new Paint();
      private Path path = new Path();
    
      public CustomClass(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5 f);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
      }
    
      @Override protected void onDraw(Canvas canvas) {
        canvas.drawPath(path, paint);
      }
    
      @Override public boolean onTouchEvent(MotionEvent event) {
        // Get the coordinates of the touch event.
        float eventX = event.getX();
        float eventY = event.getY();
    
        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
            // Set a new starting point
            path.moveTo(eventX, eventY);
            return true;
          case MotionEvent.ACTION_MOVE:
            // Connect the points
            path.lineTo(eventX, eventY);
            break;
          default:
            return false;
        }
    
        // Makes our view repaint and call onDraw
        invalidate();
        return true;
      }
    
    }

    2 In XML, paste below code

    
    
        
        
    
        
    
        
    
        

    3 Your MainActivity

    public class MainActivity extends AppCompatActivity {
    
      ImageView imageView;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.image);
      }
    
      public void saveImage(View view) {
        View v = findViewById(R.id.custom_view);
        int canvasWidth = v.getWidth();
        int canvasHeight = v.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        imageView.setImageBitmap(bitmap);
    
      }
    
    }

    That's it.

提交回复
热议问题