绘制渐变比跟随路径要复杂得多。
所以我建议你使用一些已经完成的库,而不是为你制作。
一个可以是Sc-Gauges。
有一些有用的类,而不是你可以用来实现你的目标。
首先包含库:
dependencies {
...
compile 'com.github.paroca72:sc-gauges:3.0.7'
}
使用画布创建图像或您想要的内容后:
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
现在是代码:
// Dimensions
int padding = 24;
Rect drawArea = new Rect(padding, padding, 700 - padding, 500 - padding);
// Get the main layout
ImageView imageContainer = (ImageView) this.findViewById(R.id.image);
assert imageContainer != null;
// Create a bitmap and link a canvas
Bitmap bitmap = Bitmap.createBitmap(
drawArea.width() + padding * 2, drawArea.height() + padding * 2,
Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.parseColor("#f5f5f5"));
// Create the path building a bezier curve from the left-top to the right-bottom angles of
// the drawing area.
Path path = new Path();
path.moveTo(drawArea.left, drawArea.top);
path.quadTo(drawArea.centerX(), drawArea.top, drawArea.centerX(), drawArea.centerY());
path.quadTo(drawArea.centerX(), drawArea.bottom, drawArea.right, drawArea.bottom);
// Feature
ScCopier copier = new ScCopier();
copier.setPath(path);
copier.setColors(Color.RED, Color.GREEN, Color.BLUE);
copier.setWidths(20);
copier.draw(canvas);
// Add the bitmap to the container
imageContainer.setImageBitmap(bitmap);
结果如下:
代码的第一部分仅用于创建绘制位图。
您感兴趣的是使用 ScCopier 的第二部分。
只需给出路径、颜色和搭配即可。
请注意,您在视图中可以使用onDraw 直接在视图画布上进行绘制。
这个库可以用来创建各种仪表。
如果你想看看这个网站ScComponents有一些免费的而不是仪表组件。