Android自定义视图获取像素

时间:2014-07-12 06:09:51

标签: android pixel custom-view

我有一个自定义视图,我想在ACTION_UP事件的给定位置获取像素。

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事件

1 个答案:

答案 0 :(得分:0)

您可以为该位图创建位图和画布。但你永远不会接受它。由于你从不绘制它,它将是新位图的默认值,最有可能是随机的或0。

除非您没有发布绘图代码,否则我们也需要它。