android - 以编程方式更改 ShapeDrawable 的描边宽度

标签 android drawable android-custom-view

我有一个在 XML 中定义的 ShapeDrawable,具有给定的笔划宽度和角半径。

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <stroke
        android:width="5dp"
        android:color="@color/focus_highlight" /> <!-- Color is YELLOW -->
    <corners android:radius="5dp" />
</shape>

我想以编程方式更改描边宽度和可绘制对象的颜色。我可以更改 Drawable 的颜色,但是,我无法对描边宽度和角半径执行相同的操作。有人能告诉我该怎么做吗?这是我的代码 fragment -

public class MainActivity extends Activity {
    .......
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ......
        RelativeLayout relLayout = (RelativeLayout) findViewById(R.id.relLayout);
        drawView = new DrawView(this);
        relLayout.addView(drawView);        
        .....
    }

    class DrawView extends View {
        .....
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            TypedValue value = new TypedValue();
            final boolean resolved = mContext.getTheme().resolveAttribute(
                    R.attr.acc, value, true);
            if (resolved) {
                drawable.setBounds(100, 300, 300, 500);
                drawable.setColorFilter(Color.RED, Mode.XOR); // Changed color to RED
                drawable.draw(canvas);
            }
        }
    }
}

最佳答案

您可以使用GradientDrawable为您的 View 设置描边...

GradientDrawable gd = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]{Color.BLUE, Color.GREEN});
gd.setStroke(5, Color.RED);

关于android - 以编程方式更改 ShapeDrawable 的描边宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25237196/

相关文章:

java - Android - 返回时 ListView 为空

Android 应用程序支持多种语言

Android:渐变绘制的百分比?

java - Android - 无法扩展 ImageView

android - 将 SeekBar onProgressChanged 用于自定义 View

android - 拍摄覆盖范围内的照片

java - 托管 Web 服务(Netbeans)

android - 添加新数据时,Firebase Android ChildEventListener 在 onChildAdded() 之前触发 onChildRemoved()

Android ShapeDrawable 以编程方式设置背景和边框

java - View 中的可绘制对象被压扁