問題描述
正確旋轉 ImageView 和 FrameLayout (Rotate ImageView and FrameLayout correctly)
所以我的主要目標是正確旋轉圖像(以及 CustomFrameLayout),我還需要存儲圖像的源寬度/高度。我怎樣才能做到這一點?
我試圖設置 scaleType.center / scaletype.centerInisde ,但是這是錯誤的想法。
有什麼建議嗎?謝謝!</p>
參考解法
方法 1:
Don't know if i exactly understand your problem. If u want programmatically rotate something u can try this:
ImageView image.animate().rotation(90).start();
or this
FrameLayout frame.animate().rotation(90).start();
or both. To store Width/Height u can use
int image_h = image.getHeight();
int image_w = image.getWidth();
方法 2:
Better late than never.
I was facing the exactly same problem. After some trying, I came with this solution:
private void rotateImageBy90(){
imageView.animate()
.rotation(90)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setDuration(250)
.setListener(rotateListener)
.start();
Log.d("chatImage", "Rotating image by "+90+" degrees clockwise");
}
Declare an AnimatorListener, the one that solves the problem:
Animator.AnimatorListener rotateListener = new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) imageView.getLayoutParams();
params.height = FrameLayout.LayoutParams.MATCH_PARENT;
params.width = FrameLayout.LayoutParams.MATCH_PARENT;
imageView.setLayoutParams(params);
imageView.requestLayout();
//This is the trick: I get the current bitmap, rotate it
Bitmap newBitmap = rotateImage(((BitmapDrawable)imageView.getDrawable()).getBitmap(),90);
//Then, rotate the imageview back to it's original position, without animation
imageView.setRotation(0);
//As I set the new, rotate bitmap, to it.
imageView.setImageBitmap(newBitmap);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
};
The rotateImage method:
public static Bitmap rotateImage(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix,
true);
}
(by XTL、Jotunheim、Vitor Hugo Schwaab)