4月 062019
本代码是个半成品,只作为参考
使用时,将此类作为android组件放到布局中即可
计算红线与绿线之间的角度,效果图如下:
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
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); } } |
Sorry, the comment form is closed at this time.