一个小程序:Instrumentation的使用
本来是想练习Matrix的,没想到写了一个自定义View,监听它的ASWD键后,不知道该如何按下ASWD(手机上一般都没实体按键了)。于是:
一个自定义View:
public class MyView extends View {
private final Bitmap bitmap;
private int width;
private int height;
private Matrix matrix = new Matrix();
private boolean isScale = false;
//设置倾斜度
private float sx = 0.0f;
//缩放比例
private float scale = 1.0f;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
//获得位图
bitmap = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.a)).getBitmap();
//获得位图宽
width = bitmap.getWidth();
height = bitmap.getHeight();
//当前视图获得焦点
this.setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//重置Matrix
matrix.reset();
if (!isScale) {
//旋转Matrix
matrix.setSkew(sx, 0);
} else {
matrix.setScale(scale, scale);
}
//根据原始位图和Matrix创建新图片
Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
//绘制新位图
canvas.drawBitmap(bitmap1, matrix, null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
//向左倾斜
case KeyEvent.KEYCODE_A:
isScale = false;
sx += 0.1;
postInvalidate();
break;
//向右倾斜
case KeyEvent.KEYCODE_D:
isScale = false;
sx -= 0.1;
postInvalidate();
break;
//放大
case KeyEvent.KEYCODE_W:
isScale = true;
if (scale < 2.0)
scale += 0.1;
postInvalidate();
break;
//缩小
case KeyEvent.KEYCODE_S:
isScale = true;
if (scale > 0.5)
scale -= 0.1;
postInvalidate();
break;
}
return super.onKeyDown(keyCode, event);
}
}
然后是Activity里的实现(把按钮的点击事件传递给WASD):
public class MatrixActivity extends Activity {
private Button left;
private Button right;
private Button top;
private Button bottom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matrix);
left = (Button) findViewById(R.id.left);
right = (Button) findViewById(R.id.right);
top = (Button) findViewById(R.id.top);
bottom = (Button) findViewById(R.id.bottom);
left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendKeyEvent(29);
}
});
right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendKeyEvent(32);
}
});
top.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendKeyEvent(51);
}
});
bottom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendKeyEvent(47);
}
});
}
public static void sendKeyEvent(final int KeyCode) {
new Thread() { //不可在主线程中调用
public void run() {
try {
Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}