Deep copy of a Drawable

前端 未结 4 766
旧时难觅i
旧时难觅i 2020-12-06 09:16

I have an ImageView. In its onClick I get its Drawable:

Drawable dr = ((ImageView) v).getDrawable();

And set it to a dialog\'s ImageView:

相关标签:
4条回答
  • 2020-12-06 09:49

    I managed to copy the drawable using following code:

    drawable.mutate().getConstantState().newDrawable();
    

    Here mutate() makes the drawable mutable to avoid sharing its state, and getConstantState().newDrawable() creates a new copy.

    Thus different ImageViews use different drawables and there's no stretching.

    0 讨论(0)
  • 2020-12-06 09:53

    Use BitmapFactory to convert the drawable into bitmap separately make or perform changes on it.

    0 讨论(0)
  • 2020-12-06 10:01

    You should probably call dr.clone and then call mutate() on the object

    This will make the drawable not share any state

    Drawable newdr = dr.clone();
    newdr = newdr.mutate();
    

    Edit: Maybe just

    Drawable  newdr = dr.mutate();
    

    will work. Give both a try

    0 讨论(0)
  • 2020-12-06 10:09

    Finally I succeed! I had similar problem, when I used color filter on my drawable it changed the drawable, its very close to the solution of the other people here, but only this worked for me:

    Drawable drwNewCopy = dr.getConstantState().newDrawable().mutate();
    
    0 讨论(0)
提交回复
热议问题