| /* |
| * Copyright (C) 2019 The Android Open Source Project |
| * |
| * Licensed under the Apache License, Version 2.0 (the "License"); |
| * you may not use this file except in compliance with the License. |
| * You may obtain a copy of the License at |
| * |
| * http://www.apache.org/licenses/LICENSE-2.0 |
| * |
| * Unless required by applicable law or agreed to in writing, software |
| * distributed under the License is distributed on an "AS IS" BASIS, |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| * See the License for the specific language governing permissions and |
| * limitations under the License. |
| */ |
| |
| package com.google.android.car.multidisplaytest.draw; |
| |
| 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.MotionEvent; |
| import android.view.View; |
| |
| public class CanvasView extends View { |
| private static final float TOLERANCE = 5.0f; |
| |
| private final Paint mPaint; |
| private final Path mPath; |
| private float mX; |
| private float mY; |
| |
| public CanvasView(Context c, AttributeSet attrs) { |
| super(c, attrs); |
| |
| mPath = new Path(); |
| mPaint = new Paint(); |
| mPaint.setStyle(Paint.Style.STROKE); |
| mPaint.setStrokeJoin(Paint.Join.ROUND); |
| mPaint.setStrokeWidth(4f); |
| mPaint.setColor(Color.WHITE); |
| } |
| |
| @Override |
| protected void onDraw(Canvas canvas) { |
| super.onDraw(canvas); |
| canvas.drawPath(mPath, mPaint); |
| } |
| |
| @Override |
| public boolean onTouchEvent(MotionEvent event) { |
| float x = event.getX(); |
| float y = event.getY(); |
| |
| switch (event.getAction()) { |
| case MotionEvent.ACTION_DOWN: |
| downTouch(x, y); |
| invalidate(); |
| break; |
| case MotionEvent.ACTION_MOVE: |
| moveTouch(x, y); |
| invalidate(); |
| break; |
| case MotionEvent.ACTION_UP: |
| upTouch(); |
| invalidate(); |
| break; |
| } |
| return true; |
| } |
| |
| public void clearCanvas() { |
| mPath.reset(); |
| invalidate(); |
| } |
| |
| private void moveTouch(float x, float y) { |
| float dx = Math.abs(x - mX); |
| float dy = Math.abs(y - mY); |
| if (dx >= TOLERANCE || dy >= TOLERANCE) { |
| // use mid-point as the control point of the bezier curve to make a smooth line |
| // eg. when forming curve between three non-aligned consecutive points |
| mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); |
| mX = x; |
| mY = y; |
| } |
| } |
| |
| private void downTouch(float x, float y) { |
| mPath.moveTo(x, y); |
| mX = x; |
| mY = y; |
| } |
| |
| private void upTouch() { |
| mPath.lineTo(mX, mY); |
| } |
| } |