复制一个ImageView的对anoher位图内容位图、内容、ImageView、anoher

2023-09-04 10:32:11 作者:拿红颜乱浮生

这是我百思不得其解。我需要从一个ImageView的复制位图到另一个。我不想简单地复制一个ImageView的另一个原因,我需要做一些改变的道路上比位图。

This has me baffled. I need to copy the Bitmap from one ImageView into another. I do not want to simply copy one ImageView to another because I need to do some changes to the bitmap on its way over.

下面是一些code不起作用。

Here is some code that doesn't work.

ImageView ivSrc = (ImageView) findViewById(R.id.photo);

ivSrc.setDrawingCacheEnabled(true);
    Bitmap bmSrc1 = ivSrc.getDrawingCache(); // will cause nullPointerException

    Bitmap bmSrc2 = Bitmap.createBitmap(ivSrc.getDrawingCache());//bmSrc2 will be null

    View vSrc = (View) ivSrc.getParent();
    vSrc.setDrawingCacheEnabled(true);
    Bitmap bmSrc3 = Bitmap.createBitmap(vSrc.getDrawingCache());  //black bitmap 

//要测试的位图:

//To test the bitmaps:

     ImageView ivDest = (ImageView) findViewById(R.id.photo2);
      ivDest.setImageBitmap(bmSrc1); //bmSrc1, 2, 3 results shown above

我必须要对此错误的,因为这样做的副本应该是那么容易。 TIA

I have to going about this wrong because doing a copy should be so easy. TIA

推荐答案

未使用绘图缓存,但不会需要调用buildDrawingCache()?

Not used the drawing cache, but wouldn't you need to call buildDrawingCache() ?

我会做的方式:

Bitmap bmSrc1 = ((BitmapDrawable)ivSrc.getDrawable()).getBitmap();
Bitmap bmSrc2 = bmSrc1.copy(bmSrc1.getConfig(), true);

需要注意的是bmSrc2是可变的,即你可以把它贴在画布和做任何你想用它的地方绘制它。

Note that bmSrc2 is mutable, i.e. you can stick it in a Canvas and do whatever you like with it before drawing it somewhere.