Skip to content

Instantly share code, notes, and snippets.

@jp1017
Created February 23, 2016 11:38
Show Gist options
  • Save jp1017/8fdbf99138e445db9d81 to your computer and use it in GitHub Desktop.
Save jp1017/8fdbf99138e445db9d81 to your computer and use it in GitHub Desktop.
ImageView旋转的三种方法
/**
* Camera与Matrix的比较:
* Camera的rotate()相关方法是指定某一维度上旋转指定的角度。
* Matrix的rotate()相关方法实现的效果是顺时针旋转指定的角度;与Camera指定Z轴旋转效果相同,但方向相反。
*
* Camera的translate()方法根据某一维度上视点的位移实现图像的缩放,与Matrix的scale()相关方法作用效果相似,
* 只是Matrix的scale()相关方法是直接指定缩放比例。
*
* Camera不支持倾斜操作,Matrix可以直接实现倾斜操作。
*/
private Bitmap rotateBitmapByCamera(float rotateX, float rotateY, float rotateZ, Bitmap srcBitmap){
// 1.获取处理矩阵
// 记录一下初始状态。save()和restore()可以将图像过渡得柔和一些。
// Each save should be balanced with a call to restore().
Camera camera = new Camera();
camera.save();
Matrix matrix = new Matrix();
// rotate
camera.rotateX(rotateX);
camera.rotateY(rotateY);
camera.rotateZ(rotateZ);
camera.getMatrix(matrix);
// 恢复到之前的初始状态。
camera.restore();
// 设置图像处理的中心点
matrix.preTranslate(tmpBit.getWidth() >> 1, tmpBit.getHeight() >> 1);
// matrix.postSkew(skewX, skewY);
// 直接setSkew(),则前面处理的rotate()、translate()等等都将无效。
// 2.通过矩阵生成新图像(或直接作用于Canvas)
Bitmap newBit = null;
try {
// 经过矩阵转换后的图像宽高有可能不大于0,此时会抛出IllegalArgumentException
newBit = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
return newBit;
}
/**
* ImageView先转成bitmap,然后利用Matrix旋转bitmap,这种方法不能按照中心旋转
*/
private Bitmap rotateBitmapByMatrix(Context context, Bitmap srcbBitmap, float azimuth){
Matrix matrix = new Matrix();
matrix.reset();
matrix.postRotate(azimuth);
return Bitmap.createBitmap(srcbBitmap, 0, 0,
srcbBitmap.getWidth(), srcbBitmap.getHeight(), matrix, true);
}
/**
* view的动画旋转
*/
private void rotateImageViewByAnnimation(ImageView imageView, float currentAzimuth, float azimuth){
Log.i(TAG, "will set rotation from " + currectAzimuth + " to "
+ azimuth);
Animation an = new RotateAnimation(-currectAzimuth, -azimuth,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
currectAzimuth = azimuth;
an.setDuration(500);
an.setRepeatCount(0);
an.setFillAfter(true);
imageView.startAnimation(an);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment