Android如何在视图中绘制居中形状
创始人
2024-10-10 00:01:08
0

在Android中,可以使用自定义视图来实现在居中位置绘制形状。下面是一个示例代码:

  1. 创建一个自定义视图类,继承自View:
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);
    }
}
  1. 在布局文件中添加自定义视图:


    


在以上代码中,我们创建了一个自定义视图类ShapeView,在onDraw方法中绘制一个居中的矩形。在布局文件中,我们将ShapeView放在一个LinearLayout中,并设置gravity属性为center,这样ShapeView就会在视图中居中显示。

注意,你需要将your.package.name替换为你的包名。

相关内容

热门资讯

透视肯定!aapoker辅助器... 透视肯定!aapoker辅助器怎么用(透视)ai插件(好像存在有挂);所有人都在同一条线上,像星星一...
透视软件!德州真人透视脚本(透... 透视软件!德州真人透视脚本(透视)可靠技巧(2021已更新)(哔哩哔哩)1、游戏颠覆性的策略玩法,独...
透视最新!aapoker插件(... 透视最新!aapoker插件(透视)万能辅助器(总是是真的有挂)在进入aapoker插件辅助挂后,参...
透视软件!werplan有挂吗... 透视软件!werplan有挂吗(透视)2025新版(2026已更新)(哔哩哔哩)1、实时werpla...
透视透视!aapoker怎么提... 透视透视!aapoker怎么提高中牌率(透视)插件下载(都是真的有挂);1、在aapoker怎么提高...
透视了解!拱趴大菠萝机器人(透... 透视了解!拱趴大菠萝机器人(透视)透明挂教程(2025已更新)(哔哩哔哩)1、拱趴大菠萝机器人透视辅...
透视教学!aapoker透视脚... 透视教学!aapoker透视脚本下载(透视)透视脚本下载(其实是有挂)1、任何aapoker透视脚本...
透视软件!pokemmo内置修... 透视软件!pokemmo内置修改器(透视)曝光教程(2022已更新)(哔哩哔哩)1、每一步都需要思考...
透视总结!aapoker怎么选... 透视总结!aapoker怎么选牌(透视)透视脚本下载(一贯是有挂);1、任何aapoker怎么选牌a...
透视智能ai!智星菠萝辅助(透... 透视智能ai!智星菠萝辅助(透视)攻略教程(2024已更新)(哔哩哔哩);1、起透看视 智星菠萝辅助...