ITeye博客

Bitmap和Matrix旋转图片

zhangle2612 · 2010-10-25 16:35 · Android · 移动开发 · Markdown

public class RotateImageViewActivity extends Activity {

private Button mButton1;
private Button mButton2;
private TextView mTextView;
private ImageView mImageView;
private int scaleTimes;
private int scaleAngle;


protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	
	setContentView(R.layout.rotate_image);
	
	mButton1 = (Button) findViewById(R.id.rotate_image_Button1);
	mButton2 = (Button) findViewById(R.id.rotate_image_Button2);
	mImageView = (ImageView) findViewById(R.id.rotate_image_ImageView);
	mTextView = (TextView) findViewById(R.id.rotate_image_TextView1);
	scaleTimes = 2;
	scaleAngle = 1;
	
	Log.v("Lowry", "==================="+mButton1.toString());
	
	final Bitmap mySourceBmp = BitmapFactory.decodeResource(getResources(), R.drawable.hippo); 
	final int widthOrig = mySourceBmp.getWidth();
	final int heightOrig = mySourceBmp.getHeight();
	
	mButton1.setOnClickListener(new OnClickListener(){

		public void onClick(View v) {
			scaleAngle--;
			if(scaleAngle<-5){
				scaleAngle=-5;
			}//根据旋转次数记录旋转的角度
			
			
			int newWidth = widthOrig*scaleTimes;
			int newHeight = heightOrig*scaleTimes;
			
			float scaleWidth = ((float)newWidth)/widthOrig;
			float scaleHeight = ((float)newHeight)/heightOrig;
			
			Log.i("Lowry", "++++widthOrig="+widthOrig+";heightOrig="
					+heightOrig+";newWidth="+newWidth+";newHeight="+newHeight+";scaleWidth="+scaleWidth);
			
			Matrix mt = new Matrix();
			mt.postScale(scaleWidth, scaleHeight);

//mt.setScale(2.0f,2.0f);设置图片的比例 mt.setRotate(20scaleAngle); //mt.postRotate(20scaleAngle)与其同意,设置旋转的角度 Bitmap newSizeBitmap = Bitmap.createBitmap(mySourceBmp,0,0,widthOrig,heightOrig,mt,true); //根据原来的Bitmap,mt,生成新的Bitmap对象

			BitmapDrawable bd = new BitmapDrawable(newSizeBitmap);
			
			mImageView.setImageDrawable(bd);
			mTextView.setText(Integer.toString(20*scaleAngle));
			
			
		}
		
	});
	
	
	mButton2.setOnClickListener(new OnClickListener(){
		public void onClick(View v) {
			scaleAngle++;
			if(scaleAngle>5){
				scaleAngle = 5;
			}
			
			int newWidth = widthOrig*scaleTimes;
			int newHeight = heightOrig*scaleTimes;
			
			float scaleWidth = ((float)newWidth)/widthOrig;
			float scaleHeight = ((float)newHeight)/heightOrig;
			
			
			Matrix mt = new Matrix();
			mt.postScale(scaleHeight, scaleWidth);
			mt.setRotate(20*scaleAngle);
			
			Bitmap newb = Bitmap.createBitmap(mySourceBmp,0,0, widthOrig, heightOrig, mt, true);
			
			BitmapDrawable bd = new BitmapDrawable(newb);
			
			mImageView.setImageDrawable(bd);
			
			mTextView.setText(Integer.toString(20*scaleAngle));
			
						
		}
		
	});
	

}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。