可以显示余弦函数的自定义控件

序言

终于把坐标系变化怎么玩,搞清楚了。随手写一个余弦函数的自定义控件。只有70行。

代码

package com.example.myapplication;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * <pre>
 * Created by zhuguohui
 * Date: 2024/7/1
 * Time: 14:36
 * Desc:可以绘制出Cos函数的自定义控件
 *
 * </pre>
 */
public class CosView extends View {

    private final Paint paint;
    private final Paint linePaint;
    private final Path path;

    public CosView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(5.0f);
        paint.setStyle(Paint.Style.STROKE);
        path = new Path();
        linePaint = new Paint();
        linePaint.setColor(Color.BLUE);
        linePaint.setStrokeWidth(3.0f);
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
        canvas.save();
        canvas.translate((float) width / 2, (float) height / 2);
        canvas.scale(1.0f, -1.0f);
        float mockWidth = (float) (8 * Math.PI);
        float mockHeight = 10.0f;
        float sx = width / mockWidth;
        float sy = height / mockHeight;
        float sideMax = mockWidth / 2;
        //画出坐标系
        canvas.drawLine(-(sideMax * sx), 0, sideMax * sx, 0, linePaint);
        canvas.drawLine(0, mockHeight / 2 * sy, 0, -mockHeight / 2 * sy, linePaint);

        path.reset();
        double x = -(mockWidth / 2);
        path.moveTo((float) x * sx, 0);
        for (; x < (mockWidth / 2); x += 0.01) {
            double y = Math.cos(x);
            path.lineTo((float) x * sx, (float) y * sy);
        }

        canvas.drawPath(path, paint);
        canvas.restore();
    }
}

效果

在这里插入图片描述

  • 11
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值