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替换为你的包名。

相关内容

热门资讯

微扑克有辅助挂!pokerx机... 微扑克有辅助挂!pokerx机器人,德州aapoker俱乐部外挂,黑科技教程(有挂介绍)1、超多福利...
aapoker有外挂!gg扑克... aapoker有外挂!gg扑克发牌系统,(德扑之星)竟然有挂(详细辅助线上教程)是由北京得aapok...
德州之星有辅助挂!德州ai辅助... 德州之星有辅助挂!德州ai辅助神器燃油,(aaPoker)总是真的有挂(详细辅助大神讲解);玩家必备...
微扑克ai辅助工具!约局互娱辅... 微扑克ai辅助工具!约局互娱辅助,wpk微扑克系统发牌规律,靠谱教程(有挂辅助挂)1、微扑克系统发牌...
德州ai机器人!wepoke用... 德州ai机器人赢率提升策略‌;德州ai机器人!wepoke用模拟器有什么用,(德州俱乐部)原先是真的...
WePoKe透明挂!wepok... WePoKe透明挂!wepoke有没有玄学,微扑克有辅助,介绍教程(有挂介绍),您好,WePoKe透...
wpk外挂!微扑克有没有稳赢的... wpk外挂!微扑克有没有稳赢的打法,aa扑克不能用模拟器,曝光教程(有挂透明)是一款可以让一直输的玩...
德扑之星作弊!wpk俱乐部有没... 德扑之星作弊!wpk俱乐部有没有外挂,(wepoke)起初存在有挂(详细辅助规律教程),支持语音通讯...
wepoke辅助挂!德扑之星可... wepoke辅助挂!德扑之星可以看底牌吗,微扑克软件发牌管理,wpk教程(有挂教程)1、超多福利:超...
微扑克wpk透视辅助!wpk专... 微扑克wpk透视辅助!wpk专用辅助程序,手机云扑克辅助,攻略教程(有挂详情);人气非常高,ai更新...