Implementing Rounded Rectangles with Custom Views in Android
To create a custom rounded rectangle view in Android, you must extend the View class and override its drawing methods.
First, define a new class that inherits from View. Provide the necessary constructors to handle different instantiation contexst.
// RoundedRectView.java
public class RoundedRectView extends View {
public RoundedRectView(Context ctx) {
super(ctx);
}
public RoundedRectView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
}
public RoundedRectView(Context ctx, AttributeSet attrs, int defStyle) {
super(ctx, attrs, defStyle);
}
}
The core drawing logic is placed within the onDraw method. Override this method to define how your view renders itself on the canvas.
// RoundedRectView.java
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Drawing instructions go here.
}
Inside onDraw, use a Paint object to configure the drawing style and a RectF object to define the shape's bounds. The Canvas.drawRoundRect method is then used to render the rounded retcangle.
// RoundedRectView.java
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint shapePaint = new Paint();
shapePaint.setAntiAlias(true); // Enable smooth edges
shapePaint.setColor(Color.BLUE); // Set the fill color
// Define the rectangle's area to match the view's size
RectF bounds = new RectF(0, 0, getWidth(), getHeight());
float cornerRadius = 30f; // Radius for the rounded corners
canvas.drawRoundRect(bounds, cornerRadius, cornerRadius, shapePaint);
}