2010年7月5日星期一

利用Matrix類旋轉位圖(bitmap)

本練習利用Matrix類的setRotate()方法, 通過Bitmap.createBitmap()方法從一個源位圖創建另一個複製的位圖, 從而做到旋轉的效果.

利用Matrix類旋轉位圖(bitmap)

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
>
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10px"
android:id="@+id/rotatebar"
android:max="360"
android:progress="0"
/>
</LinearLayout>
<ImageView
android:id="@+id/imageview"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
/>
</LinearLayout>


AndroidImage.java
package com.AndroidImage;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.SeekBar;

public class AndroidImage extends Activity {

private ImageView myImageView;
private float scale, rotateDegree;
private Bitmap bitmap;
int bmpWidth, bmpHeight;
SeekBar rotateBar;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

myImageView = (ImageView)findViewById(R.id.imageview);
rotateBar = (SeekBar)findViewById(R.id.rotatebar);

bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
bmpWidth = bitmap.getWidth();
bmpHeight = bitmap.getHeight();
scale = 1;
rotateDegree = 0;

loadImage();

rotateBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
rotateDegree = (float)progress;
loadImage();
}
});
}

private void loadImage(){

Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
matrix.setRotate(rotateDegree);

Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
myImageView.setImageBitmap(scaledBitmap);

}
}




沒有留言:

發佈留言