2014-07-12 57 views
0

我有一個自定義視圖,我想在ACTION_UP事件中獲得給定位置的像素。Android customview獲得像素

public class MyView extends View 
{ 
    private Bitmap mBitmap; 
    private Canvas mCanvas; 
    private Paint mPaint; 

    public MyView(Context context) 
    { 
     super(context); 
    } 

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

     setDrawingCacheEnabled(true); 

     mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 
     mCanvas = new Canvas(mBitmap); 

     mPaint = new Paint(); 
     mPaint.setColor(Color.RED); 
     mPaint.setAntiAlias(true); 
     mPaint.setDither(true); 
     mPaint.setStrokeWidth(20f); 
     mPaint.setStyle(Paint.Style.STROKE); 
     mPaint.setStrokeJoin(Paint.Join.ROUND); 
     mPaint.setStrokeCap(Paint.Cap.ROUND); 
    } 

    @Override 
    protected void onDraw(Canvas canvas) 
    { 
     canvas.drawBitmap(mBitmap, 0, 0, mPaint); 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) 
    { 
     switch (event.getAction()) 
     { 
      case MotionEvent.ACTION_UP: 
      { 
       float x = event.getX(); 
       float y = event.getY(); 

       int pixel = mBitmap.getPixel((int) x, (int) y); 

       Log.i("APP", "Pixel is: " + pixel); 

       return true; 
      } 
     } 

     return super.onTouchEvent(event); 
    } 
} 

我只獲得了0當我打電話mBitmap.getPixel(x, y);

enter image description here

  • 我已經標有黑色圓圈中的圖像上的ontouch事件

回答

0

你創建一個位圖,以及該位圖的畫布。但你永遠不會去吸引它。既然你永遠不會畫它,它將會是一個新位圖的默認值是什麼,它最可能是隨機的或0.

除非你沒有發佈繪圖代碼,在這種情況下,我也需要這個。