android 自定义View六芒星(六角星)

绘制六角星视图
本文介绍了一个自定义视图类Xing2View,该类继承自CustomView,用于在Android环境中绘制两个不同大小的六角星。文章详细展示了如何通过计算顶点坐标并使用Path对象来绘制六角星,并在中心绘制一个圆形。

这里写图片描述

public class Xing2View extends CustomView {

    public Xing2View(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mDeafultPaint.setAntiAlias(true);//抗锯齿
        canvas.translate(mViewWidth / 2, mViewHeight / 2);//移动画布到页面中心
        canvas.rotate(-90);
//        6角星外接圆大小
        int t = mViewWidth / 3;
//        6角星6个角的角度360/6

        canvas.drawColor(Color.BLACK);
        canvaXing(t,canvas);
        canvaXing((int) (t*0.8),canvas);

    }


    private void canvaXing(int t,Canvas canvas){
        float r = 60;
//        弧度的计算公式为: 2*PI/360*角度;
        double aa = 2 * PI / 360;
//        计算6个顶点坐标
        float a[] = {(float) (Math.cos(0 * aa) * t), (float) (sin(0 * aa) * t)};
        float b[] = {(float) (Math.cos(r * aa) * t), (float) (sin(r * aa) * t)};
        float c[] = {(float) (Math.cos(r * 2 * aa) * t), (float) (sin(r * 2 * aa) * t)};
        float d[] = {(float) (Math.cos(r * 3 * aa) * t), (float) (-sin(r * 3 * aa) * t)};
        float e[] = {(float) (Math.cos(r * 4 * aa) * t), (float) (sin(r * 4 * aa) * t)};
        float f[] = {(float) (Math.cos(r * 5 * aa) * t), (float) (sin(r * 5 * aa) * t)};
//        画6角星
        mDeafultPaint.setStrokeWidth(2);
        mDeafultPaint.setColor(Color.YELLOW);
        mDeafultPaint.setStyle(Paint.Style.STROKE);
        Path path = new Path();
        path.moveTo(a[0], a[1]);
        path.lineTo(c[0], c[1]);
        path.lineTo(e[0], e[1]);
        path.close();
        path.moveTo(b[0], b[1]);
        path.lineTo(d[0], d[1]);
        path.lineTo(f[0], f[1]);
        path.close();
        canvas.drawPath(path, mDeafultPaint);

        canvas.drawCircle(0,0,t,mDeafultPaint);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魑魅魍魉9527

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值