将包含渐变的drawable xml转换为位图

时间:2018-03-13 07:33:15

标签: android android-canvas android-drawable android-bitmap

我想将渐变应用于位图。到目前为止,我正在使用这种技术。 这是我在MainActivity.class的onCreate方法中的代码。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        double angle = Math.toRadians(135);
        double length = 100;
        int x = (int) (Math.cos(angle) * length);
        int y = (int) (Math.sin(angle) * length);


        int[] colors = new int[3];
        colors[0] = Color.parseColor("#FF4081");
        colors[1] = Color.parseColor("#3F51B5");

        Bitmap bitmap = Bitmap.createBitmap(1080, 1080, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);

        LinearGradient linearGradient =
                new LinearGradient(0, 0, x, y, colors[1], colors[0], Shader.TileMode.CLAMP);

        Paint paint = new Paint();
        paint.setDither(true);
        paint.setShader(linearGradient);

        canvas.drawRect(new RectF(0, 0, 1080, 1080), paint);

        ImageView imageView = findViewById(R.id.iv);
        imageView.setImageBitmap(bitmap);
    }
}

导致此

enter image description here

但我希望得到像这样的效果

enter image description here

图像2结果是通过使用以下代码

简单地创建可绘制XML文件来实现的
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:angle="45"
        android:endColor="@color/colorPrimary"
        android:startColor="@color/colorAccent" />
</shape>

并将其设置为ImageView的背景,但我想在位图上使用此效果,因为我想将该位图本地保存为图像。我尝试在MainActivity中创建一个GradientDrawable实例,并在post

中提到的GradientDrawable上调用onDraw(canvas)

1 个答案:

答案 0 :(得分:1)

如我所见,你计算的角度不正确。

而不是这个

 LinearGradient linearGradient =
            new LinearGradient(0, 0, x, y, colors[1], colors[0], Shader.TileMode.CLAMP);

使用此

LinearGradient linearGradient =
            new LinearGradient(1080, 0, 0, 1080, colors[1], colors[0], Shader.TileMode.CLAMP);

x0是渐变开始X,y0是渐变开始Y,x1是渐变结束X,y1是渐变结束Y.

希望我帮助过你。