渐变一词在此上下文中(如在许多图形编辑器中,包括 Photoshop)指的是多种颜色之间的平滑过渡,而不是仅使用一种颜色填满一个区域。
Android API 提供 3 种不同的渐变:LinearGradient、RadialGradient 和 SweepGradient。
这些都是Shader 的子类。您可以在Paint 对象上设置Shader,然后使用该Paint 绘制任何形状。根据渐变的类型,形状将填充颜色和它们之间的过渡。
例如:
可以使用以下代码生成此图像:
Bitmap test = Bitmap.createBitmap(640, 200, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(test);
{ // draw a dark gray background
Paint backgroundPaint = new Paint();
backgroundPaint.setARGB(255, 24, 24, 24);
c.drawPaint(backgroundPaint);
}
Path heart = new Path();
{ // prepare a heart shape
heart.moveTo(110, 175);
heart.lineTo(10, 75);
RectF leftCircle = new RectF(10, 25, 110, 125);
heart.arcTo(leftCircle, 180, 180);
RectF rightCircle = new RectF(110, 25, 210, 125);
heart.arcTo(rightCircle, 180, 180);
heart.close();
}
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(18f);
int[] colors = {
0xFFFFFF88, // yellow
0xFF0088FF, // blue
0xFF000000, // black
0xFFFFFF88 // yellow
};
float[] positions = {0.0f, 0.33f, 0.66f, 1.0f};
{ // draw the left heart
SweepGradient sweepGradient;
{ // initialize the sweep gradient
sweepGradient = new SweepGradient(50, 50, colors, positions);
paint.setShader(sweepGradient);
}
c.drawPath(heart, paint);
c.drawText("SweepGradient", 50, 190, paint);
}
{ // draw the middle heart
LinearGradient linearGradient;
{ // initialize a linear gradient
linearGradient = new LinearGradient(250, 0, 350, 150, colors, positions, Shader.TileMode.CLAMP);
paint.setShader(linearGradient);
}
heart.offset(210, 0); // move the heart shape to the middle
c.drawPath(heart, paint);
c.drawText("LinearGradient", 260, 190, paint);
}
{ // draw the right heart
RadialGradient radialGradient;
{ // initialize a linear gradient
radialGradient = new RadialGradient(550, 50, 100, colors, positions, Shader.TileMode.CLAMP);
paint.setShader(radialGradient);
}
heart.offset(210, 0); // move the heart shape to the right
c.drawPath(heart, paint);
c.drawText("RadialGradient", 470, 190, paint);
}
{ // save the bitmap
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "test.png";
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
test.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
所以 LinearGradient 在 Photoshop 中是 Linear Gradient,RadialGradient 是 Radial Gradient,SweepGradient 是 Angular Gradient,如您在第三个参考中所述。我建议首先在图像编辑器中尝试这些(所有流行的图像编辑器都有这些工具),您很快就会了解它们的工作原理。
您也可以在 XML drawable 中使用这些渐变(就像在您的第 4 次参考中一样),但最多只能使用 3 种颜色。
在SweepGradient 中,提供位置时,0.0 点在 3 点钟方向,顺时针方向(0.25 在 6 点钟方向,0.5 在 9 点钟方向,0.75 在 12 点钟方向)时钟,3 点钟返回 1.0)。
关于你的结论:
- 如您所见,任何形状都可以用
SweepGradient 绘制,而不仅仅是一个环。在上面的例子中,即使是标签也是用渐变绘制的。
- 是的,时钟的指针类比恰到好处。
- 在用法上,
SweepGradient 与LinearGradient 非常相似,只是您不需要提供TileMode,因为您不能超出颜色列表的范围。
- 是的,您需要提供中心点的坐标。
我希望这能解决问题。