1.代码如下:
public class MyView extends View { //初始化图片资源 private Bitmap bitmap; //Matrix private Matrix matrix = new Matrix(); //倾斜度 private float sx = 0.0f; //位图宽高 private int width , height; //缩放比例 private float scale = 1.0f; //判断缩放还是倾斜 private boolean isScale = false; 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.reset(); if (! isScale){ //倾斜 matrix.setSkew(sx , 0); } else { //缩放 matrix.setScale(scale , scale); } //将matix的变换放入之前的位图,得到新的位图,并绘制出来 Bitmap bitmap2 = Bitmap.createBitmap(bitmap , 0 , 0 , width , height , matrix , true); canvas.drawBitmap(bitmap2 , 0 ,0 ,null); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (event.getKeyCode()){ 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); } }
然后在布局中使用即可.
2.一些解释如下:
matrix.setScale(scale , scale) : 这个比较好理解,参数为x.y的缩放比例,大于1则放大。
matrix.setSkew(sx , 0) :这个分两种情况
sx > 0 时:
sx < 0 时 :
可以看到y坐标的倾斜距离一直为0,所以所有点的Y坐标并没有变化,只有x坐标变化了,才有了倾斜的效果.