Deep copy of a Drawable

谁说胖子不能爱 提交于 2019-12-17 16:32:43

问题


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

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

And set it to a dialog's ImageView:

zoomedImage.setImageDrawable(dr);

But when I close the dialog or the activity is resumed. The image at the original position gets stretched and is shown larger than its size, leading to only a portion of the image is visible in the ImageView.

Is this a case of deep copy or there is another problem? If it is, how can do I deep copy the original Drawable so that I could set the copy to zoomed image?

Thanks in advance.


回答1:


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();



回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/13064473/deep-copy-of-a-drawable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!