android - 如何动态地将笔画添加到可绘制对象?
问题描述
我使用函数 drawCircle() 来返回一个椭圆形的 ShapeDrawable 对象,并使用 ImageView.setImageDrawable() 来设置它。但是如何向椭圆形可绘制对象添加 2dp 边框?我尝试使用 GrandientDrawable 但无论边框厚度的值有多大,在模拟器上几乎看不到边框。
这是我的函数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.STROKE);
drawable.setIntrinsicHeight(diameter);
drawable.setIntrinsicWidth(diameter);
return drawable;
}
这是我的函数 setStroke():
public void setStroke(ImageView view) {
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.OVAL);
gradientDrawable.setStroke(100, Color.WHITE);
view.setBackground(gradientDrawable);
}
这是我如何使用它:
// Calculate diameter
int selector_one_diameter = (int)(selector_diameter * 1/6);
// Get ImageView
ImageView one_img = (ImageView) findViewById(R.id.circle_one_selector_img);
// Set drawable
one_img.setImageDrawable(drawCircle(selector_one_diameter));
// Set stroke
setStroke(one_img);
解决方案
在drawable文件夹下创建一个oval.xml文件并使用dashWidth和width而不是gradientDrawable怎么样?
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:dashWidth="2dp"
android:width ="3dp"
android:color="@color/colorPrimary"/>
</shape>
推荐阅读
- java - 如何在消费者 Java 8 中抛出异常
- c# - ViewModel 不更新表单 (Xamarin.Forms)
- json - 实现自定义Newtonsoft JsonConverter(阅读器)
- django - 如何过滤查询集以获取由另一个字段中的每个值分组的一个字段中的最大值?
- android - Flutter 如何在后台发现蓝牙设备(flutter_bluetooth_serial)
- python - 像浏览器一样访问私有 github 页面(使用 Python)
- java - 如何以粗体显示 TableViewer 标题列中的文本?
- android - 尺寸线间距
- spring-boot - RabbitMQ:覆盖路由键
- parse-platform - PFObject saveInBackground progressBlock 的语法