• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 /**
26  * The view that draws the spring as it reacts (i.e. expands/compresses) to the user touch.
27  */
28 public class SpringView extends View {
29     final Paint mPaint = new Paint();
30     private float mLastHeight = 175;
31 
SpringView(Context context, AttributeSet attrs)32     public SpringView(Context context, AttributeSet attrs) {
33         super(context, attrs);
34         setWillNotDraw(false);
35         mPaint.setColor(context.getResources().getColor(R.color.springColor));
36         mPaint.setStrokeWidth(10);
37     }
38 
39     /**
40      * Sets the other end of the spring.
41      *
42      * @param height height of the mass, which is used to derive how to draw the spring
43      */
setMassHeight(float height)44     public void setMassHeight(float height) {
45         mLastHeight = height;
46         invalidate();
47     }
48 
49     @Override
onDraw(Canvas canvas)50     public void onDraw(Canvas canvas) {
51         // Draws the spring
52         // 30px long, 15 sections
53         int num = 20;
54         float sectionLen = 150; // px
55         final float x = canvas.getWidth() / 2;
56         float y = 0;
57         float sectionHeight = mLastHeight / num;
58         float sectionWidth = (float) Math.sqrt(sectionLen * sectionLen
59                 - sectionHeight * sectionHeight);
60         canvas.drawLine(x, 0, x + sectionWidth / 2, sectionHeight / 2, mPaint);
61         float lastX = x + sectionWidth / 2;
62         float lastY = sectionHeight / 2;
63         for (int i = 1; i < num; i++) {
64             canvas.drawLine(lastX, lastY, 2 * x - lastX, lastY + sectionHeight, mPaint);
65             lastX = 2 * x - lastX;
66             lastY = lastY + sectionHeight;
67         }
68         canvas.drawLine(lastX, lastY, x, mLastHeight, mPaint);
69     }
70 }
71