Moving bitmap on canvas

前端 未结 1 677
花落未央
花落未央 2021-02-06 11:34

I have an imageView, canvas, and a button.. when I click the button a bitmap gets drawn on the canvas

I want to move that bitmap using my onTouch ( drag the bitmap to an

1条回答
  •  天涯浪人
    2021-02-06 11:49

     public class MainActivity extends Activity
    {
      @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        DrawingView dv = new DrawingView(this);
        setContentView(dv);
    }
    
    class DrawingView extends View{
    Bitmap bitmap;
    
    float x,y;
    
    public DrawingView(Context context)
    {
     super(context);
     bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
    }
    
    
    public boolean onTouchEvent(MotionEvent event)
    {
    
     switch(event.getAction())
        {
       case MotionEvent.ACTION_DOWN: {
    
       }
       break;
    
       case MotionEvent.ACTION_MOVE: 
       {
          x=(int)event.getX();
          y=(int)event.getY();
    
     invalidate();
     }
    
     break;
       case MotionEvent.ACTION_UP: 
    
           x=(int)event.getX();
           y=(int)event.getY();
           System.out.println(".................."+x+"......"+y); //x= 345 y=530 
           invalidate();
        break; 
       }
      return true;
     }
    
     @Override
     public void onDraw(Canvas canvas)
     {
     Paint paint = new Paint();
     paint.setStyle(Paint.Style.FILL);
     paint.setColor(Color.CYAN);
     canvas.drawBitmap(bitmap, x, y, paint);  //originally bitmap draw at x=o and y=0
     }
     }
     }
    

    At the star bitmap is draw at x=0 and y=0; On drag x and y changes so call inavlidate to refresh drate. On touch up draw the bitmap at the dragged position x and y and call invalidate to refresh draw.

    Bitmap drawn at x=0 y=0. on drag and drop //x= 345 y=530. The resulting snap shot is attached.

    You need to make sure your image does not look like going out of screen at the screen edges Check if x is within screenwidth - bitmapwidth and y is less than screenheight - bitmapheight. i have not included those conditions in the code.

    enter image description here

    EDIT:

          setContentView(R.layout.main);    
          LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
          DrawingView dv= new DrawingView(this);
          ll.addView(dv);
    

    0 讨论(0)
提交回复
热议问题