1 package com.google.android.DemoKit; 2 3 import android.content.Context; 4 import android.content.res.Resources; 5 import android.graphics.Canvas; 6 import android.graphics.Color; 7 import android.graphics.Paint; 8 import android.graphics.drawable.Drawable; 9 import android.util.AttributeSet; 10 import android.view.View; 11 12 public class JoystickView extends View { 13 14 private Drawable mJoystickBackground; 15 private Drawable mJoystickPressed; 16 private Drawable mJoystickNormal; 17 18 private int fX; 19 private int fY; 20 Boolean fPressed; 21 private Paint mLabelPaint; 22 private String mLabelText; 23 JoystickView(Context context)24 public JoystickView(Context context) { 25 super(context); 26 initJoystickView(context); 27 } 28 JoystickView(Context context, AttributeSet attrs)29 public JoystickView(Context context, AttributeSet attrs) { 30 super(context, attrs); 31 initJoystickView(context); 32 } 33 setPosition(int x, int y)34 public void setPosition(int x, int y) { 35 fX = x; 36 fY = y; 37 mLabelText = String.format("%d,%d", fX, fY); 38 invalidate(); 39 } 40 setPressed(boolean pressed)41 public void setPressed(boolean pressed) { 42 fPressed = pressed; 43 invalidate(); 44 } 45 initJoystickView(Context context)46 private void initJoystickView(Context context) { 47 fX = fY = 0; 48 fPressed = false; 49 Resources r = context.getResources(); 50 mJoystickBackground = r.getDrawable(R.drawable.joystick_background); 51 int w = mJoystickBackground.getIntrinsicWidth(); 52 int h = mJoystickBackground.getIntrinsicHeight(); 53 mJoystickBackground.setBounds(0, 0, w, h); 54 mJoystickPressed = r.getDrawable(R.drawable.joystick_pressed_holo_dark); 55 mJoystickNormal = r.getDrawable(R.drawable.joystick_normal_holo_dark); 56 Utilities.centerAround(w / 2 - 4, h / 2 + 4, mJoystickNormal); 57 Utilities.centerAround(w / 2 - 4, h / 2 + 4, mJoystickPressed); 58 mLabelPaint = new Paint(); 59 mLabelPaint.setColor(Color.WHITE); 60 mLabelPaint.setTextSize(24); 61 mLabelPaint.setAntiAlias(true); 62 mLabelPaint.setShadowLayer(1, 2, 2, Color.BLACK); 63 setPosition(0, 0); 64 } 65 66 @Override onDraw(Canvas canvas)67 protected void onDraw(Canvas canvas) { 68 mJoystickBackground.draw(canvas); 69 Drawable indicator = fPressed ? mJoystickPressed : mJoystickNormal; 70 int w = mJoystickBackground.getIntrinsicWidth(); 71 int h = mJoystickBackground.getIntrinsicHeight(); 72 int x = w / 2 - 4 + fX; 73 int y = h / 2 + 4 + fY; 74 Utilities.centerAround(x, y, indicator); 75 indicator.draw(canvas); 76 canvas.drawText(mLabelText, x + 12, y + 8, mLabelPaint); 77 } 78 79 @Override onMeasure(int widthMeasureSpec, int heightMeasureSpec)80 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 81 setMeasuredDimension(mJoystickBackground.getIntrinsicWidth(), 82 mJoystickBackground.getIntrinsicHeight()); 83 } 84 85 } 86