序言
终于把坐标系变化怎么玩,搞清楚了。随手写一个余弦函数的自定义控件。只有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();
}
}