【问题标题】:Set imageview foreground gradient color programmatically以编程方式设置 imageview 前景渐变颜色
【发布时间】:2016-12-28 12:15:44
【问题描述】:

我这里有 xml 渐变可绘制资源文件:

文件:fg_graidient

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <gradient
        android:type="linear"
        android:centerX="0%"
        android:startColor="#00020321"
        android:centerColor="#F2000000"
        android:endColor="#B2020321"
        android:angle="45"/>
</shape>

我可以像下面这样的 imageview 前景:

<ImageView
            android:id="@+id/backimg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:scaleType="fitXY"
            android:foreground="@drawable/fg_graidient"
            />

但我想以编程方式为 imageview 设置这个可绘制的前景。有可能吗?

【问题讨论】:

    标签: java android xml android-layout gradient


    【解决方案1】:

    以编程方式创建渐变形状

    ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            LinearGradient lg = new LinearGradient(0, 0, width, height,
                new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
                new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);
            return lg;
        }
    };
    
    PaintDrawable p=new PaintDrawable();
    p.setShape(new RectShape());
    p.setShaderFactory(sf);
    

    使用

    Button btn= (Button)findViewById(R.id.btn);
    btn.setBackgroundDrawable((Drawable)p);
    

    【讨论】:

      【解决方案2】:

      试试这个片段:

       ImageView img = (ImageView)findViewById(R.id.backimg);
              img.setImageResource(R.drawable.fg_graidient);
      

      【讨论】:

      • img.setImageResource 会替换我的imageview,而不是给图片背景或前景添加渐变,所以是绝对错误的
      猜你喜欢
      • 2014-10-25
      • 2012-09-25
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 2011-09-01
      • 1970-01-01
      相关资源
      最近更新 更多