簡體   English   中英

以編程方式設置imageview前景漸變顏色

[英]Set imageview foreground gradient color programmatically

我在這里有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設置此可繪制前景。 可能嗎?

以編程方式創建漸變形狀

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);

試試這個代碼段:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM