java:
package EX04_25.txt;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
public class EX04_25 extends Activity {
private Button LButton;
private Button RButton;
private ImageView mImageView;
private int degrean = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initApp();
}
private void initApp() {
LButton = (Button)findViewById(R.id.leftButton);
RButton = (Button)findViewById(R.id.rightButton);
mImageView = (ImageView)findViewById(R.id.myImage);
final Bitmap bmp= BitmapFactory.decodeResource
(getResources(), R.drawable.woman);
final int mWidth = bmp.getWidth();
final int mHeight = bmp.getHeight();
mImageView.setScaleType(ScaleType.CENTER); //这项设置为正常旋转Bitmap的关键
// TODO Auto-generated method stub
LButton.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
turnLeft();
}
private void turnLeft() {
// TODO Auto-generated method stub
degrean--;
if (degrean < -5) {
degrean = -5;
}
Matrix mt = new Matrix();
mt.postRotate(5*degrean);
Bitmap turnBmp = Bitmap.createBitmap(bmp, 0, 0, mWidth, mHeight, mt, true);
mImageView.setImageBitmap(turnBmp);
}
});
RButton.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
turnRight();
}
private void turnRight() {
// TODO Auto-generated method stub
degrean++;
if (degrean > 5) {
degrean = 5;
}
Matrix mt = new Matrix();
mt.postScale(1, 1);
mt.setRotate(5*degrean);
Bitmap turnBmp = Bitmap.createBitmap(bmp, 0, 0, mWidth, mHeight, mt, true);
BitmapDrawable turnDrawable = new BitmapDrawable(turnBmp);
mImageView.setImageDrawable(turnDrawable);
}
});
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id = "@+id/leftButton"
android:layout_marginTop = "40dip"
android:layout_marginLeft = "20dip"
android:layout_width="81dip"
android:layout_height="wrap_content"
android:text="向左旋转"
/>
<ImageView
android:id = "@+id/myImage"
android:layout_marginTop = "10dip"
android:layout_marginLeft = "10dip"
android:layout_width="100dip"
android:layout_height="125dip"
android:src = "@drawable/woman"
/>
<Button
android:id = "@+id/rightButton"
android:layout_marginTop = "40dip"
android:layout_marginLeft = "10dip"
android:layout_width="80dip"
android:layout_height="wrap_content"
android:text="向右旋转"
/>
</LinearLayout>