欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android自定义View实现心形图案

程序员文章站 2022-07-05 09:49:55
本文实例为大家分享了android自定义view实现心形的具体代码,供大家参考,具体内容如下通过继承view实现的❤形在绘制心形需要path类中的两个重要方法分别是:moveto、cub...

本文实例为大家分享了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" />

实现效果:

Android自定义View实现心形图案

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关标签: Android 心形