加入收藏 | 设为首页 | 会员中心 | 我要投稿 东莞站长网 (https://www.0769zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 系统 > 正文

Android自定义View完成心形图案

发布时间:2021-11-07 07:47:42 所属栏目:系统 来源:互联网
导读:本文实例为大家分享了Android自定义View实现心形的具体代码,供大家参考,具体内容如下 通过继承View实现的形 在绘制心形需要Path类中的两个重要方法分别是:moveTo、cubicTo moveTo 不会进行绘制,只用于移动移动画笔。 lineTo 用于进行直线绘制。 quadTo 用
本文实例为大家分享了Android自定义View实现心形的具体代码,供大家参考,具体内容如下
 
通过继承View实现的❤形
在绘制心形需要Path类中的两个重要方法分别是:moveTo、cubicTo
 
moveTo 不会进行绘制,只用于移动移动画笔。
 
lineTo 用于进行直线绘制。
 
quadTo 用于绘制圆滑曲线,即贝塞尔曲线。
 
cubicTo 同样是用来实现贝塞尔曲线的。
 
具体实现:
 
public class HeartView extends View {
    private int mMeasureWidth;
    private int mWidthMode;
    private int mMeasureHeight;
    private int mHeightMode;
    private Paint paint;
 
    public HeartView(Context context) {
        super(context);
    }
 
    public HeartView(Context context, AttributeSet attrs) {
        super(context, attrs);
 
        paint = new Paint();//实例画笔
        paint.setAntiAlias(true);//抗锯齿
        paint.setStrokeWidth(2);//画笔宽度
        paint.setColor(Color.RED);//画笔颜色
        paint.setStyle(Paint.Style.FILL);//画笔样式
    }
 
    /**
     * 测量
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        mHeightMode = MeasureSpec.getMode(heightMeasureSpec);
        mMeasureWidth = MeasureSpec.getSize(widthMeasureSpec);
        mMeasureHeight = MeasureSpec.getSize(heightMeasureSpec);
        if (mWidthMode == MeasureSpec.AT_MOST && mHeightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(200, 200);
        } else if (mWidthMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(200, mMeasureHeight);
        } else if (mHeightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mMeasureWidth, 200);
        } else {
            setMeasuredDimension(mMeasureWidth, mMeasureHeight);
        }
    }
 
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
 
        int width = getWidth();//获取屏幕宽
        int height = getHeight();//获取屏幕高
 
        /**
         *  绘制心形
         */
        //左半面
        Path path = new Path();
        path.moveTo(width / 2, height / 4);
        path.cubicTo((width * 6) / 7, height / 9, (width * 12) / 13, (height * 2) / 5, width / 2, (height * 7) / 12);
        canvas.drawPath(path, paint);
        //右半面
        Path path2 = new Path();
        path2.moveTo(width / 2, height / 4);
        path2.cubicTo(width / 7, height / 9, width / 13, (height * 2) / 5, width / 2, (height * 7) / 12);
        canvas.drawPath(path2, paint);
 
    }
}
在布局中引入一下
 
<com.xxb.cache.weight.HeartView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

(编辑:东莞站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读