如何在Android中每次单击都在ImageView上绘制矩形

时间:2019-11-30 16:02:55

标签: java android

我想每次点击都在ImageView上绘制矩形。这是我的代码。当我单击旧矩形时,将其删除,但我想保存它。

public class MainActivity extends AppCompatActivity {

    Canvas canvas;
    Paint paint;
    ImageView img;
    Bitmap bmp;
    float x,y;
    int point_x,point_y,left,top,right,bottom,i,j,i2,j2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        img=findViewById(R.id.img);
        img.setDrawingCacheEnabled(true);
        img.buildDrawingCache();


        }
        public boolean onTouchEvent(MotionEvent event){
            paint=new Paint();
            paint.setColor(Color.RED);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(5);
            x=event.getX();
            y=event.getY();
            point_x=(int)x;
            point_y=(int)y;
            left=point_x-10;
            top=point_y-215;
            right=point_x+125;
            bottom=point_y-65;
            bmp=Bitmap.createBitmap(img.getDrawingCache());
            canvas=new Canvas(bmp);
            canvas.drawRect(left,top,right,bottom,paint);
            img.setImageBitmap(bmp);
            return true;

        }



    }

0 个答案:

没有答案