android - 如何从VectorDrawable获取位图-LMLPHP

我仍在尝试解决几天前以来遇到的问题,但仍然没有找到解决方案。但是,我要逐步到达那里。现在,我遇到了另一个障碍。

我正在尝试获取Bitmap.getpixel(int x, int y),以返回用户使用Color触摸过的内容的OnTouchListener。馅饼是VectorDrawable资源,vectordrawable.xml我还不需要对像素数据做任何事情,我只需要对其进行测试。因此,我制作了一个TextView,它将吐出触摸过的Color

public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    TextView textView;

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

        imageView = (ImageView) findViewById(R.id.imageView);
        textView = (TextView) findViewById(R.id.textView);

        imageView.setOnTouchListener(imageViewOnTouchListener);
    }

    View.OnTouchListener imageViewOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {

            Drawable drawable = ((ImageView)view).getDrawable();
            //Bitmap bitmap = BitmapFactory.decodeResource(imageView.getResources(),R.drawable.vectordrawable);
            Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

            int x = (int)event.getX();
            int y = (int)event.getY();

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

            textView.setText("touched color: " + "#" + Integer.toHexString(pixel));

            return true;
        }
    };
}

但是,一旦我触摸ImageView,发出“不幸的是,...”消息并退出,我的应用程序就会遇到致命错误。在堆栈跟踪中,我发现了这一点。
java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
    at com.skwear.colorthesaurus.MainActivity$1.onTouch(MainActivity.java:38)

而第38行就是这一行,
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

我有点关注this。我究竟做错了什么?是因为它是VectorDrawable。我该怎么做才能获得Color?您可以看到我还尝试了BitmapFactory来强制转换Drawable。由于VectorDrawable的API级别是像API 21一样被添加的,这也可能是一个问题吗?

最佳答案

首先,您不能将VectorDrawable转换为BitmapDrawable。他们没有亲子关系。它们都是Drawable类的直接子类。

现在,要从drawable中获取位图,您将需要从drawable元数据中创建一个Bitmap

在单独的方法中大概可能是这样的,

try {
    Bitmap bitmap;

    bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
} catch (OutOfMemoryError e) {
    // Handle the error
    return null;
}

我希望这有帮助。

09-28 04:33