1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.support.animation; 18 19 import android.content.Context; 20 import android.graphics.Canvas; 21 import android.graphics.Paint; 22 import android.util.AttributeSet; 23 import android.view.View; 24 25 import org.jspecify.annotations.NonNull; 26 27 /** 28 * The view that draws the spring as it reacts (i.e. expands/compresses) to the user touch. 29 */ 30 public class SpringView extends View { 31 final Paint mPaint = new Paint(); 32 private float mLastHeight = 175; 33 SpringView(Context context, AttributeSet attrs)34 public SpringView(Context context, AttributeSet attrs) { 35 super(context, attrs); 36 setWillNotDraw(false); 37 mPaint.setColor(context.getResources().getColor(R.color.springColor)); 38 mPaint.setStrokeWidth(10); 39 } 40 41 /** 42 * Sets the other end of the spring. 43 * 44 * @param height height of the mass, which is used to derive how to draw the spring 45 */ setMassHeight(float height)46 public void setMassHeight(float height) { 47 mLastHeight = height; 48 invalidate(); 49 } 50 51 @Override onDraw(@onNull Canvas canvas)52 public void onDraw(@NonNull Canvas canvas) { 53 // Draws the spring 54 // 30px long, 15 sections 55 int num = 20; 56 float sectionLen = 150; // px 57 final float x = canvas.getWidth() / 2; 58 float sectionHeight = mLastHeight / num; 59 float sectionWidth = (float) Math.sqrt(sectionLen * sectionLen 60 - sectionHeight * sectionHeight); 61 canvas.drawLine(x, 0, x + sectionWidth / 2, sectionHeight / 2, mPaint); 62 float lastX = x + sectionWidth / 2; 63 float lastY = sectionHeight / 2; 64 for (int i = 1; i < num; i++) { 65 canvas.drawLine(lastX, lastY, 2 * x - lastX, lastY + sectionHeight, mPaint); 66 lastX = 2 * x - lastX; 67 lastY = lastY + sectionHeight; 68 } 69 canvas.drawLine(lastX, lastY, x, mLastHeight, mPaint); 70 } 71 } 72