我正在尝试使用 imageview 矩阵随机缩放和旋转图像,请参见下面的代码。我遇到了两个问题,可能相关也可能不相关。
第一:旋转不起作用,图像出现没有任何旋转。
第二:缩放起作用,在图像被重新缩放的范围内。但是,如果比例常数大于 1,则图像的一部分被切掉,因此只有部分图像出现在屏幕上。我认为这与 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.
}
}