最近公司有个需求,在一个安卓板子上实现人脸识别,关键这个安卓板子是厂家自制的,横屏拍照之后的取的人脸图片,显示的“歪了”。为了显示效果,使ImageView控件显示旋转之后的人脸图像。
1.旋转bitmap:
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.ic_launcher)).getBitmap();
Matrix matrix = new Matrix();
// 旋转90度
matrix.setRotate(90);
Bitmap new = Bitmap.create(bitmap,0,bitmap.getWidth(),0,bitmap.getHeight(),matrix);
image.setBitmapResource(bitmap);
注:如果程序不断获取新的bitmap重新设置给ImageView的话,那么bitmap在不断旋转,不回收内存,效率很低。
2.使用ImageView自带的旋转方法
可以通过在xml中设置ImageView的属性来实现,这种方式很简单。
<!-- ImageView中的属性-->
android:rotation="90"
或者使用Java代码动态调用旋转方法:
// 使旋转点在图片中心
image.setPivotX(image.getWidth()/2);
image.setPivotY(image.getHeight()/2);
// 旋转90度
image.setRotation(90);
3.使用旋转动画
旋转效果同样可以让ImageView配合属性动画来实现
// 旋转90度
rotateImage.animate().rotation(90);
或者使用普通动画:
Animation rotateAnimation = new RotateAnimation(lastAngle, progress, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1);
rotateAnimation.setFillAfter(true);
rotateAnimation.setDuration(50);
rotateAnimation.setRepeatCount(0);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateImage.startAnimation(rotateAnimation);
具体多少度可以根据自身的情况处理。