我想按进度绘制像这张图片一样的自定义drawrect:
但是,我的问题是将左上角的起点更改为中上角,到目前为止,这是我的自定义 View :
public class RoundProgress extends View {
Path path = new Path();
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
float length;
float[] intervals = {0, 0};
public RoundProgress(Context context) {
super(context);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(100);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
path.reset();
RectF rect = new RectF(0, 0, w, h);
float inset = paint.getStrokeWidth();
rect.inset(inset, inset);
path.addRoundRect(rect, 100, 100, Path.Direction.CCW);
length = new PathMeasure(path, false).getLength();
intervals[0] = intervals[1] = length;
PathEffect effect = new DashPathEffect(intervals, length);
paint.setPathEffect(effect);
}
public void setProgress(int progress) {
PathEffect effect = new DashPathEffect(intervals, length - length * progress / 100);
paint.setPathEffect(effect);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
}
任何人都知道如何改变它?我已经尝试更改 path.move(x, y) 但它不起作用。
最佳答案
对于所有不喜欢猜测的人来说,没有办法改变用 addRoundedRect
创建的圆角矩形的起点。
改为使用自定义路径绘制它:
fun createRoundedRectWithCustomStartPoint(viewWidth: Float, viewHeight: Float) {
val radius = 20f
val strokeWidthHalf = paint.strokeWidth/2
val top = strokeWidthHalf
val start = strokeWidthHalf
path.apply {
moveTo(viewWidth/2, top)
lineTo(viewWidth - radius, top)
arcTo(viewWidth - 2 * radius, top, viewWidth, 2 * radius, -90F, 90F, false)
lineTo(viewWidth, radius)
arcTo(viewWidth - 2 * radius, viewHeight - 2 * radius, viewWidth, viewHeight, 0F, 90F, false)
lineTo(radius, viewHeight)
arcTo(start, viewHeight - 2 * radius, 2 * radius, viewHeight, 90F, 90F, false)
lineTo(start, radius)
arcTo(start, top, 2 * radius, 2 * radius, 180F, 90F, false)
lineTo(viewWidth/2, top)
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
path.reset()
createRoundedRectWithCustomStartPoint(viewWidth = w.toFloat()-paint.strokeWidth/2,viewHeight = h.toFloat()-paint.strokeWidth/2)
length = PathMeasure(path, false).length
intervals[1] = length
intervals[0] = intervals[1]
val effect: PathEffect = DashPathEffect(intervals, length)
paint.pathEffect = effect
}
关于android - 如何更改起点drawrect customview android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39556867/