Search code examples
javaandroidimageviewclonedeep-copy

How do you copy an ImageView to another ImageView?


Say, ImageView i1 has an image in it and i want to copy ImageView i1 to ImageView i2 not just refer i2 to i1 but actually copy.

ImageView i2 = new ImageView(context);
i2 = i1;    //i2 only refers to i1

if there is a class and we are passing ImageView as a parameter of its constructor

public class CopyEx{
public ImageView i2;

public CopyEx(ImageView i, Context c){
   i2 = new ImageView(c);
   i2 = i;    //This also only refers to i and not copy it
}
}

The only thing that seems to work is doing

i2.setImageDrawable(i1.getDrawable());
and
i2.setTag(i1.getTag());

So is there a way to copy an ImageView?


Solution

  • Use this for copy

    BitmapDrawable drawable = (BitmapDrawable) imageView1.getDrawable();
    Bitmap bitmap = drawable.getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    

    And use this for pasting

    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    ImageView image2 = (ImageView) findViewById(R.id.imageView2);
    image2.setImageBitmap(bmp);