繁体   English   中英

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

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

我使用函数drawCircle(int diameter)返回ShapeDrawable对象,它是一个OvalShape。 然后,我使用ImageView.setImageDrawable()设置OvalShape。 但是ImageViews仍然为空。 如何正确做?

函数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;
    }

设置ImageView

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

最重要的是,我尝试使用.xml文件描述椭圆形。 但是由于dimens.xml值无法用Java代码重写,因此我无法动态更改椭圆形的大小。 如果您可以提出其他建议,那就再好不过了!

这可能是由于您尚未设置绘制对象的高度,高度。 您可以使用以下代码设置默认大小。

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

暂无
暂无

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

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