以下是在StackOverFlow上找到的答案,记录一下。
private Bitmap addGradient(Bitmap originalBitmap) {
int width = originalBitmap.getWidth();
int height = originalBitmap.getHeight();
Bitmap updatedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(updatedBitmap);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Paint paint = new Paint();
int[] colors = new int[4];
switch (mColor) {
case BLUE:
colors[0] = 0xFF2E8CFF;
colors[1] = 0xFF2E8CFF;
colors[2] = 0xFF24DFED;
colors[3] = 0xFF24DFED;
break;
case PURPLE:
colors[0] = 0xFF8F4AD4;
colors[1] = 0xFF8F4AD4;
colors[2] = 0xFF5742CE;
colors[3] = 0xFF5742CE;
break;
case LIGHT_GREEN:
colors[0] = 0xFF2EE0FF;
colors[1] = 0xFF2EE0FF;
colors[2] = 0xFF24EDC4;
colors[3] = 0xFF24EDC4;
break;
}
float[] positions = new float[]{0.25f, 0.5f, 0.75f, 1};
LinearGradient shader = new LinearGradient(0, 0, 0,
height, colors, positions, Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawRect(0, 0, width, height, paint);
return updatedBitmap;
}
效果图: