为了账号安全,请及时绑定邮箱和手机立即绑定

Android 自定义View 绘制正N边形

标签:
Android

支付宝芝麻信用分-分析中,有个正五边形,刚刚有空试着做了下
效果图:
图片描述

分析图:
图片描述

实现原理、步骤:
已知半径为R,圆心点O(a,b),点A(a, c=b-R), OA=OB=R,圆心角O的度数
1) 求出弦AB的长度
2) 利用两点间距离公式,得到两个方程AB、OB相关的,解出y的值
3) 将y代入其中一个方程,解出x的值 (我这里代入的是AB的方程)
4) 利用canvas旋转,循环绘制

package com.stone.canvaspath.zhima;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * 正N边形
 * author : stone
 * email  : aa86799@163.com
 * time   : 2016/11/17 14 12
 */

public class ZhimaView extends View {

    private Paint mPaint;
    private float mR, mCx, mCy;
    private static final int mN = 9;
    private static final float DEGREES_UNIT = 360 / mN; //正N边形每个角  360/mN能整除

    public ZhimaView(Context context) {
        this(context, null);
    }

    public ZhimaView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZhimaView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mPaint = new Paint();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        float mW = getMeasuredWidth();
        float mH = getMeasuredHeight();

        mCx = mW / 2;
        mCy = mH / 2;
        mR = Math.min(mCx, mCy) / 4 * 3;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mPaint.setColor(Color.BLUE);
        mPaint.setStyle(Paint.Style.STROKE);

        float d = (float) (2 * mR * Math.sin(Math.toRadians(DEGREES_UNIT / 2)));
        float c = mCy - mR;
        float y = (d * d + mCy * mCy - c * c - mR * mR) / (2 * (mCy - c));
        float x = (float) (mCx + Math.sqrt(-1 * c * c + 2 * c * y + d * d - y * y));

        for (int i = 0; i < mN; i++) {
            canvas.save();
            canvas.rotate(DEGREES_UNIT * i, mCx, mCy);
            canvas.drawLine(mCx, mCy, mCx, c, mPaint);
            canvas.drawLine(mCx, c, x, y, mPaint);
            canvas.restore();
        }
    }
}

本人不定期分享自定义View的一些效果实现,csdn博客地址:http://blog.csdn.net/jjwwmlp456

点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
10
获赞与收藏
106

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消