动态旋转图片(Bitmap与Matrix 旋转ImageView)
新建一个继承Activity类的BitmapMatrixActivity,并设置布局文件为:bitmapmatrix.xml。
在布局文件中添加一个ImageView 和2个Button:left和right
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" >
<Button android:id="@+id/bitmapmatrix_btn01" style="@android:style/Widget.Button.Inset" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/left" />
<Button android:id="@+id/bitmapmatrix_btn02" style="@android:style/Widget.Button.Inset" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/right" /> </LinearLayout>
<ImageView android:id="@+id/bitmapmatrix_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon_001" /> |
而后在Activity代码中设置:
package lyx.feng.second;
import lyx.feng.simpletextdemo.R; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView;
public class BitmapMatrixActivity extends Activity implements OnClickListener { private Button left = null; private Button right = null; private ImageView image = null; private Bitmap bitmap = null; private float rote = 1.0f;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.bitmapmatrix); this.left = (Button) super.findViewById(R.id.bitmapmatrix_btn01); this.right = (Button) super.findViewById(R.id.bitmapmatrix_btn02); this.image = (ImageView) super.findViewById(R.id.bitmapmatrix_image);
// 得到Bitmap实例 this.bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_001);
// 注册单击按钮 this.left.setOnClickListener(this); this.right.setOnClickListener(this); }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.bitmapmatrix_btn01: // 左旋转操作 left(); break; case R.id.bitmapmatrix_btn02: // 右旋转操作 right(); break; } }
private void left() { // 左旋转操作 int bitmapHeight = bitmap.getHeight(); int bitmapWidth = bitmap.getWidth(); this.rote -= Math.PI / 10; Matrix matrix = new Matrix(); // 设置旋转参数 matrix.postRotate(rote, bitmapWidth / 2, bitmapHeight / 2 + right.getHeight()); // 得到缩小后的图片 Bitmap temp = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true); this.image.setImageBitmap(temp); // 回收Bitmap temp = null;
}
private void right() { // 放大操作 int bitmapHeight = bitmap.getHeight(); int bitmapWidth = bitmap.getWidth(); this.rote += Math.PI / 10; Matrix matrix = new Matrix(); // 设置旋转参数 matrix.postRotate(rote, bitmapWidth / 2, bitmapHeight / 2 + right.getHeight()); // 得到缩小后的图片 Bitmap temp = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true); this.image.setImageBitmap(temp); // 回收Bitmap temp = null; }
}
|