本文实例为大家分享了android使用贝塞尔曲线画心形的具体代码,供大家参考,具体内容如下
一开始我只是想画个圆,可画着画着就成了心形,那就将错就错
1. 创建一个activity
relativelayout container = findviewbyid(r.id.download_container); displaymetrics metrics = new displaymetrics(); getwindowmanager().getdefaultdisplay().getmetrics(metrics); devicewidth = metrics.widthpixels; deviceheight = metrics.heightpixels; circle circle = new circle(this, devicewidth / 2, deviceheight / 2, devicewidth / 8); line line = new line(this, devicewidth / 2, deviceheight / 2, devicewidth / 8); container.addview(line);
2. 创建一个自定义的view
import android.content.context; import android.graphics.canvas; import android.graphics.color; import android.graphics.paint; import android.graphics.path; import android.graphics.pointf; import android.view.view; public class line extends view { private paint mpaint; private pointf startpointf; private pointf endpointf; private pointf controlpointf1, controlpointf2; private pointf startpointf2; private pointf endpointf2; private pointf controlpointf3, controlpointf4; public line(context context, float x, float y, float radius) { super(context); double d = (2 * math.sqrt(2) - 1); this.startpointf = new pointf(x, y - radius); this.endpointf = new pointf(x, y + radius / 10); this.controlpointf1 = new pointf(x, (float) (y - d * radius)); this.controlpointf2 = new pointf((float) (x + d * radius), (float) (y - d * radius)); this.startpointf2 = new pointf(x, y - radius); this.endpointf2 = new pointf(x, y + radius / 10); this.controlpointf3 = new pointf(x, (float) (y - d * radius)); this.controlpointf4 = new pointf((float) (x - d * radius), (float) (y - d * radius)); this.mpaint = new paint(paint.anti_alias_flag); this.mpaint.setcolor(color.white); } @override protected void ondraw(canvas canvas) { super.ondraw(canvas); //绘制贝塞尔曲线 path path = new path(); path.moveto(startpointf.x, startpointf.y); path.cubicto(controlpointf1.x, controlpointf1.y, controlpointf2.x, controlpointf2.y, endpointf.x, endpointf.y); canvas.drawpath(path, mpaint); path.moveto(startpointf2.x, startpointf2.y); path.cubicto(controlpointf3.x, controlpointf3.y, controlpointf4.x, controlpointf4.y, endpointf2.x, endpointf2.y); canvas.drawpath(path, mpaint); } }
运行效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。