简体   繁体   English

如何动态地将可绘制资源设置为ImageView?

[英]How to dynamically set drawable resource to ImageView?

I use function drawCircle(int diameter) to return ShapeDrawable object, which is an OvalShape. 我使用函数drawCircle(int diameter)返回ShapeDrawable对象,它是一个OvalShape。 Then I use ImageView.setImageDrawable() to set the OvalShape. 然后,我使用ImageView.setImageDrawable()设置OvalShape。 But the ImageViews are still empty. 但是ImageViews仍然为空。 How to do it correctly? 如何正确做?

Function drawCircle() : 函数drawCircle()

public ShapeDrawable drawCircle (int diameter) {
        OvalShape ovalShape = new OvalShape();
        ShapeDrawable drawable = new ShapeDrawable(ovalShape);
        drawable.getPaint().setColor(getResources().getColor(R.color.textColorHint));
        drawable.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
        drawable.getPaint().setStrokeWidth((float)2);
        drawable.setBounds(0 ,0, diameter, diameter);

        return drawable;
    }

Set ImageView : 设置ImageView

one_img.setImageDrawable(drawCircle(selector_one_diameter));
two_img.setImageDrawable(drawCircle(selector_two_diameter));

Above all, I tried using .xml file to describe oval shapes. 最重要的是,我尝试使用.xml文件描述椭圆形。 But since values in dimens.xml cannot be re-written in Java code, I can't dynamically change the size of oval shapes. 但是由于dimens.xml值无法用Java代码重写,因此我无法动态更改椭圆形的大小。 It couldn't be better if you can suggest another way! 如果您可以提出其他建议,那就再好不过了!

It could be due to you have not set widht, height to your drawable. 这可能是由于您尚未设置绘制对象的高度,高度。 You can set a default size using below code. 您可以使用以下代码设置默认大小。

drawable.setIntrinsicWidth(); 
drawable.setIntrinsicHeight();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM