2014-04-07 71 views
0

我試圖在畫布的第一次觸摸時在畫布上繪製BMP,但問題在於BMP在我觸摸屏幕時隨處跳動。我想要的是BMP保持固定在第一次觸摸的位置,我不知道如何做到這一點。android:在畫布上放置bmp

@Override 
protected void onDraw(Canvas canvas) { 
super.onDraw(canvas); 
canvas.drawBitmap(mBarn, mTouchX, mTouchY, mPaint); 
invalidate(); 
} 

public boolean onTouchEvent(MotionEvent event) { 
int eventAction = event.getAction(); 

switch (eventAction) { 
    case MotionEvent.ACTION_DOWN: 
     mTouchX = (int)event.getX(); 
     mTouchY = (int)event.getY();      
     break; 

    case MotionEvent.ACTION_MOVE: 
     break; 

    case MotionEvent.ACTION_UP: 
     break; 
} 
invalidate(); 
return true;  

}

+0

使用一個布爾值來告訴你,如果你已經通過觸摸屏幕了。 如果布爾值爲true,則不在onTouch()內部進行任何操作。否則,請觸摸Event並將您的布爾值設置爲true。 – joao2fast4u

回答

0
package com.example.graphics1; 


import android.os.Bundle; 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.view.Menu; 
import android.view.MotionEvent; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 
import android.view.View; 
import android.view.View.OnTouchListener; 

public class MainActivity extends Activity implements OnTouchListener{ 
MyBringBack ourView; 
float x,y; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ourView = new MyBringBack(this); 
    ourView.setOnTouchListener(this); 
    x=0; 
    y=0; 
    setContentView(ourView); 
} 
    public class MyBringBack extends SurfaceView implements Runnable 
    { 
     SurfaceHolder ourholder; 
     Thread ourThread = null; 
     boolean isrunning=true; 
     public MyBringBack(Context context) { 
      super(context); 
      // TODO Auto-generated constructor stub 
      ourholder = getHolder(); 
      ourThread = new Thread(this); 
      ourThread.start(); 
     } 

     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      while(isrunning) 
      { 
       if(!ourholder.getSurface().isValid()) 
        continue; 
       Canvas canvas = ourholder.lockCanvas(); 
       canvas.drawRGB(255, 255, 255); 
       if(x!=0 && y!=0) 
       { 
        Bitmap bitmap = 
     BitmapFactory.decodeResource(getResources(), R.drawable.images); 
        canvas.drawBitmap(bitmap, x- 
     (bitmap.getWidth()/2), y-(bitmap.getHeight()/2), null); 
       } 
       ourholder.unlockCanvasAndPost(canvas); 
      } 
     } 

    } 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

@Override 
public boolean onTouch(View arg0, MotionEvent arg1) { 
    // TODO Auto-generated method stub 
    x=arg1.getX(); 
    y=arg1.getY();  
    return true; 
} 

    } 

Use this code this will help you..