首页 > 解决方案 > 如何动态地将笔画添加到可绘制对象?

问题描述

我使用函数 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);

标签: androidandroid-drawable

解决方案


在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>


推荐阅读