Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android贝塞尔曲线画心形

Android使用贝塞尔曲线画心形

作者:「已注销」

这篇文章主要为大家详细介绍了Android使用贝塞尔曲线画心形,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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);
    }
}

运行效果

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

您可能感兴趣的文章:
阅读全文