在Android中,可以使用自定义视图来实现在居中位置绘制形状。下面是一个示例代码:
public class ShapeView extends View {
private Paint mPaint;
private int mShapeColor;
private int mShapeWidth;
private int mShapeHeight;
public ShapeView(Context context) {
super(context);
init();
}
public ShapeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mShapeColor = Color.RED;
mShapeWidth = 200;
mShapeHeight = 200;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int left = centerX - mShapeWidth / 2;
int top = centerY - mShapeHeight / 2;
int right = centerX + mShapeWidth / 2;
int bottom = centerY + mShapeHeight / 2;
mPaint.setColor(mShapeColor);
canvas.drawRect(left, top, right, bottom, mPaint);
}
}
在以上代码中,我们创建了一个自定义视图类ShapeView,在onDraw方法中绘制一个居中的矩形。在布局文件中,我们将ShapeView放在一个LinearLayout中,并设置gravity属性为center,这样ShapeView就会在视图中居中显示。
注意,你需要将your.package.name
替换为你的包名。