package com.bcoder.widgets;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class AngleCalcView extends View {
private static final String LOG_TAG = "AngleCalcView";
private List<PointF> mPoints = new ArrayList<>();
private Paint mPointPaint;
private Paint mBaseLinePaint;
public AngleCalcView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mPointPaint = new Paint();
mPointPaint.setStrokeWidth(2);
mPointPaint.setColor(Color.RED);
mPointPaint.setTextSize(20);
mBaseLinePaint = new Paint();
mBaseLinePaint.setStrokeWidth(5);
mBaseLinePaint.setColor(Color.GREEN);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
//666, 749,这是view中心的坐标,因为只是临时测试,我手动获取添加到程序的
float centerX = 666;
float centerY = 749;
canvas.drawLine(centerX, centerY, centerX, getHeight(), mBaseLinePaint);
for(int i = 0; i < mPoints.size(); i++){
Log.d(LOG_TAG, "x: " + mPoints.get(i).x + ", y: " + mPoints.get(i).y);
canvas.drawPoint(mPoints.get(i).x, mPoints.get(i).y, mPointPaint);
double a = (mPoints.get(i).x - centerX) / (mPoints.get(i).y - centerY);
double b = Math.atan(a) / Math.PI * 180;
canvas.drawText(String.format("%.2f", b), mPoints.get(i).x + 10, mPoints.get(i).y, mPointPaint);
canvas.drawLine(centerX, centerY, mPoints.get(i).x, mPoints.get(i).y, mPointPaint);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
mPoints.add(new PointF(event.getX(), event.getY()));
}
invalidate();
return super.dispatchTouchEvent(event);
}
}