Trong trường hợp bạn cần vẽ (trên canvas) một vòng tròn với bán kính khác nhau cho các góc khác nhau, bạn có thể sử dụng điều này:
private void drawAsymmetricRoundRect(Canvas canvas, RectF rectF, float[] radii, Paint paint) {
float topLeftX = rectF.left + radii[0];
float topLeftY = rectF.top + radii[0];
float topRightX = rectF.right - radii[1];
float topRightY = rectF.top + radii[1];
float bottomRightX = rectF.right - radii[2];
float bottomRightY = rectF.bottom - radii[2];
float bottomLeftY = rectF.bottom - radii[3];
float bottomLeftX = rectF.left + radii[3];
RectF topLeftCorner = new RectF(rectF.left, rectF.top, topLeftX + radii[0], topLeftY + radii[0]);
RectF topRightCorner = new RectF(topRightX - radii[1], rectF.top, rectF.right, topRightY + radii[1]);
RectF bottomRightCorner = new RectF(bottomRightX - radii[2], bottomRightY - radii[2], rectF.right, rectF.bottom);
RectF bottomLeftCorner = new RectF(rectF.left, bottomLeftY - radii[3], bottomLeftX + radii[3], rectF.bottom);
canvas.drawArc(topLeftCorner, 180, 90, true, paint);
canvas.drawArc(topRightCorner, 270, 90, true, paint);
canvas.drawArc(bottomRightCorner, 0, 90, true, paint);
canvas.drawArc(bottomLeftCorner, 90, 90, true, paint);
canvas.drawRect(topLeftX, rectF.top, topRightX, bottomLeftY < bottomRightY ? bottomLeftY : bottomRightY, paint); //top rect
canvas.drawRect(topLeftX > bottomLeftX ? topLeftX : bottomLeftX, topRightY, rectF.right, bottomRightY, paint); //right rect
canvas.drawRect(bottomLeftX, topLeftY > topRightY ? topLeftY : topRightY, bottomRightX, rectF.bottom, paint); //bottom rect
canvas.drawRect(rectF.left, topLeftY, bottomRightX < topRightX ? bottomRightX : topRightX, bottomLeftY, paint); //left rect
}
float[] radii
là một mảng float (chiều dài = 4), mà các cửa hàng kích thước của bán kính góc của bạn (chiều kim đồng hồ, bắt đầu từ góc trên bên trái =>{topLeft, topRight, bottomRight, bottomLeft}
).
Về cơ bản, cách tiếp cận này vẽ 4 vòng cung (góc) và lấp đầy mọi thứ ở giữa các góc đó với 4 thước.
LƯU Ý QUAN TRỌNG: Tôi đã đặt khởi tạo các góc RectFs
trong phương pháp này để giảm độ phức tạp của mã được đăng. Do thực tế bạn có thể gọi phương thức này từ phương thức onDraw()
của mình, bạn nên trích xuất phần này của mã và đặt nó ở nơi bạn bắt đầu khác Rects
(miễn là bạn cũng không khởi tạo chúng trong onDraw()
: P) .
Điều này có thể hữu ích - http://developer.android.com/reference/android/graphics/drawable/shapes/RoundRectShape.html – Varun
@Varun Tôi cần thêm một chút thông tin sau đó? Các tài liệu của dev không phải luôn luôn thân thiện khi bạn muốn một cái gì đó cụ thể này. – KickingLettuce