android - 部分图像消失,使用矩阵运算旋转不起作用

标签 android android-imageview image-rotation

我正在尝试使用 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/

相关文章:

2019 年 1 月 29 日之后创建的带有 API KEY 的 Android Place Picker

Android VpnService 类及其构建器类

android - 如何在 Eclipse 中禁用 Logcat?

android - 来自画廊的图像自动旋转 - Android

python - pygame中的旋转命中框矩形

java - Android 头显 "NASA daily image App"

android - TextView 可以同时具有背景和图像吗

android - 在 ListView 上方添加图像

python - 在 Matplotlib 中旋转图像

java - 图像在 3D 空间中绕 Y 轴旋转