您的位置:首页 > 其它

使用 Matrix控制图片的变换

2016-06-25 13:26 302 查看
自定义 View 代码

package com.test.matrixtest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;

/**
* Created by Administrator on 2016/6/25.
*/
public class MyView extends View
{
private Bitmap mBitmap; //初始的图片资源

Matrix mMatrix = new Matrix(); // Matrix 实例化对象

private  float sx = 0.0f; //设置初始 倾斜度

private  float scale = 1.0f; //缩放比例

private  int width , height;  //位图的宽高

private boolean isScale = false; //判断是否为缩放的 标记

public MyView(Context context, AttributeSet attrs) {
super(context, attrs);

//获取位图
mBitmap = ((BitmapDrawable)context.getResources().getDrawable(R.mipmap.a)).getBitmap();

//获取位图的宽和高
width = mBitmap.getWidth();
height = mBitmap.getHeight();

//让当前View获得焦点
setFocusable(true);

}

@Override
protected void onDraw(Canvas canvas) {

//重置 matrix
mMatrix.reset();
if (!isScale){

//旋转 matrix
mMatrix.setSkew(sx, 0);
}else{
//缩放 matrix
mMatrix.setScale(scale,scale);
}

//根据原始位图和 Matrix 创建新图片
Bitmap newBitmap =  Bitmap.createBitmap(mBitmap, 0, 0, width, height, mMatrix, true);

//对新位图进行绘制
canvas.drawBitmap(newBitmap,mMatrix,null);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

switch (keyCode){
//向左倾斜
case KeyEvent.KEYCODE_A :
isScale = false;
sx += 0.1;
postInvalidate(); //表示在非UI线程中 刷新 界面
break;

//向右倾斜
case KeyEvent.KEYCODE_D :
isScale = false;
sx -= 0.1;
postInvalidate(); //表示在非UI线程中 刷新 界面
break;

//放大
case KeyEvent.KEYCODE_W :
isScale = true;
if (scale<2.0){
scale+=0.1;
}
postInvalidate(); //表示在非UI线程中 刷新 界面
break;

//缩小
case KeyEvent.KEYCODE_S :
isScale = true;
if (scale>0.5){
scale -= 0.1;
}
postInvalidate(); //表示在非UI线程中 刷新 界面
break;
}

return super.onKeyDown(keyCode, event);
}
}


package com.test.matrixtest;

import android.app.Activity;
import android.os.Bundle;

/**
* 矩阵效果 Matrix
*/
public class MatrixActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matrix);
}

}


布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.test.matrixtest.MatrixActivity">

<com.test.matrixtest.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: