1 /* 2 * Copyright (C) 2023 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.vdmdemo.demos; 18 19 import android.content.Context; 20 import android.graphics.Canvas; 21 import android.graphics.Color; 22 import android.graphics.Paint; 23 import android.graphics.Paint.Style; 24 import android.util.AttributeSet; 25 import android.util.Log; 26 import android.util.TypedValue; 27 import android.view.View; 28 29 import androidx.annotation.Nullable; 30 31 /** A view rendering a simple counter that is incremented every time onDraw() is called. */ 32 public class CounterView extends View { 33 34 private static final String TAG = "CounterView"; 35 private static final int TEXT_SIZE_SP = 100; 36 private long mCounter = 0; 37 private final Paint mTextPaint = new Paint(); 38 CounterView(Context context)39 public CounterView(Context context) { 40 super(context); 41 init(); 42 } 43 CounterView(Context context, @Nullable AttributeSet attrs)44 public CounterView(Context context, @Nullable AttributeSet attrs) { 45 super(context, attrs); 46 init(); 47 } 48 CounterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr)49 public CounterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 50 super(context, attrs, defStyleAttr); 51 init(); 52 } 53 CounterView( Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes)54 public CounterView( 55 Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 56 super(context, attrs, defStyleAttr, defStyleRes); 57 init(); 58 } 59 init()60 private void init() { 61 mTextPaint.setColor(Color.RED); 62 mTextPaint.setStyle(Style.FILL); 63 mTextPaint.setTextSize(computeScaledTextSizeInPixels()); 64 } 65 66 @Override onDraw(Canvas canvas)67 protected void onDraw(Canvas canvas) { 68 canvas.drawText(String.valueOf(mCounter), 0, 200, mTextPaint); 69 Log.e(TAG, "Rendered counter: " + mCounter); 70 mCounter++; 71 } 72 computeScaledTextSizeInPixels()73 private float computeScaledTextSizeInPixels() { 74 return TypedValue.applyDimension( 75 TypedValue.COMPLEX_UNIT_SP, 76 TEXT_SIZE_SP, 77 getContext().getResources().getDisplayMetrics()); 78 } 79 } 80