【问题标题】:setRotation change the ImageView positionsetRotation 改变 ImageView 的位置
【发布时间】:2021-05-15 01:10:44
【问题描述】:

在下面的代码中,我尝试用 imageView 替换贴纸,保持贴纸的 [宽度、高度、TranslateX、TranslateY 和旋转] 相同imageView

            transX = selectedSticker.getTransX();
            transY = selectedSticker.getTransY();
            rotation = selectedSticker.getCurrentAngle();
            
            ImageView mHoverView = findViewById(R.id.drawingView);
            mHoverView.setLayoutParams(new FrameLayout.LayoutParams((int) stickerWidth, (int) stickerHeight));
            
            mHoverView.setTranslationX(transX);
            mHoverView.setTranslationY(transY);
            mHoverView.setRotation(rotation);
            mHoverView.setImageResource(R.drawable.dog);
            mHoverView.setBackgroundColor(Color.BLUE);

当我点击REPLACE按钮将贴纸替换为imageView时,一切正常,问题开始当我旋转时贴纸并点击 REPLACE 按钮,imageView 与贴纸进行相同的旋转,但它设置在错误的位置(imageView 未围绕其中心旋转) :

例如

无旋转:

旋转:

【问题讨论】:

    标签: java android android-imageview image-rotation


    【解决方案1】:

    也许,你必须通过重新计算与 View 的变换兼容的变换矩阵来获得正确的平移值。

    //mHoverView.setTranslationX(transX);
    //mHoverView.setTranslationY(transY);
    
    Matrix m = new Matrix();
    m.setTranslate(transX, transY);
    m.postRotate(rotation);
    float[] offset = { 0.0F, 0.0F };
    m.mapPoints(offset);
    
    mHoverView.setTranslationX(offset[0]);
    mHoverView.setTranslationY(offset[1]);
    

    【讨论】:

    • 非常感谢您的回答,不幸的是,它不起作用,现在mHoverView失去了旋转角度并定位在错误的位置
    • 哦,原来如此。那我就不知道了。问题的原因必须存在于您帖子中未显示的代码的另一部分。
    【解决方案2】:

    问题是我没有设置 PivotXPivotY 所以视图没有围绕中心旋转,这是完整的代码:

    float[] values = new float[9];
    selectedSticker.getMatrix().getValues(values);
    float dx = values[2];
    float dy = values[5];
    mHoverView.setPivotX(0.0f);
    mHoverView.setPivotY(0.0f);
    mHoverView.setTranslationX(dx);
    mHoverView.setTranslationY(dy);
    mHoverView.setRotation(rotation);
    mHoverView.invalidate();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      相关资源
      最近更新 更多