代码之家  ›  专栏  ›  技术社区  ›  abbyshk

将包含渐变的可绘制xml转换为位图

  •  2
  • abbyshk  · 技术社区  · 7 年前

    我想对位图应用渐变。到目前为止,我正在使用这种技术。 这是我在MainActivity的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实例,并在GradientDrawable上调用onDraw(canvas),如 post

    1 回复  |  直到 7 年前
        1
  •  1
  •   Artur Akhnoyan    7 年前

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

    而不是这个

     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。

    希望我能帮助你。