我正在尝试使用 imageview 矩阵随机缩放和旋转图像,请参见下面的代码。我遇到了两个问题,它们可能相关也可能不相关。
首先:旋转不起作用,图像没有任何旋转。
第二:缩放有效,在一定程度上图像被重新缩放。然而,如果比例常数大于一,则图像的一部分被切掉,从而只有一部分图像出现在屏幕上。我认为这与 imageView 的边框有关,但我该如何解决?
预先感谢您的帮助!
final ImageView imageView = getImageView(); //Help function that provides imageViews
if(imageView == null) return;
Matrix imageMatrix = imageView.getImageMatrix();
imageMatrix.postRotate(randGen.nextFloat()*360);
float randomScale = randGen.nextFloat()*1.5f + 0.5f;
imageMatrix.postScale(randomScale, randomScale);
imageView.setImageBitmap(usedBitmap);
imageView.setImageMatrix(imageMatrix);
imageView.setScaleType(ScaleType.MATRIX);
RelativeLayout.LayoutParams layPar = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layPar.leftMargin = pCenter.x; //pCenter is the point where the image is drawn.
layPar.topMargin = pCenter.y;
relativeLayout.addView(imageView, layPar);
更新:我遇到这个问题已经有一段时间了,我没有找到使用上述方法的解决方案,所以我尝试将 View 子类化。这是我的 View 子类,图像既没有旋转也没有缩放。我真的不明白为什么这些解决方案不起作用。有人吗?
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.View;
public class ScaleRotateView extends View {
Bitmap image;
float rotation;
float scaleX;
float scaleY;
public ScaleRotateView(Context context, Bitmap image, float rotation, float scaleX, float scaleY) {
super(context);
this.image = image;
this.rotation = rotation;
this.scaleX = scaleX;
this.scaleY = scaleY;
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawBitmap(image, 0, 0, new Paint());
Matrix matrix = canvas.getMatrix();
matrix.preRotate(rotation, image.getWidth()/2, image.getHeight()/2);
matrix.setScale(scaleX, scaleY);
canvas.setMatrix(matrix);
//I also tried using canvas.rotate() and canvas.scale, but to no avail.
}
}
最佳答案
您可以在自定义 View 的 onDraw 方法中尝试
Matrix transform = new Matrix();
transform.setTranslate(dx, dy);//
transform.preRotate(degree,PivotX ,PivotY);
canvas.drawBitmap(bitmap, transform, null);
关于android - 部分图像消失,使用矩阵运算旋转不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10011498/