【问题标题】:Android: ImageView Rotation ScaleAndroid:ImageView 旋转比例
【发布时间】:2012-01-23 18:26:36
【问题描述】:

我有一个 imageView,我基本上是在尝试制作一个温度计风格的仪表。我在下面添加了一张图片进行测试,我基本上是在尝试旋转图片。第一张图片具有标准布局中的图像。尝试旋转图像后,宽度仍会填满屏幕,但会缩小图像以为角落腾出空间,使实际图像显得更小。我希望图像保持完全相同的大小,但根据传递给它的 Matrix 进行旋转。

这是我用于旋转的代码:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);        

    circle = (ImageView) findViewById(R.id.imageView1);
    Bitmap myImg = BitmapFactory.decodeResource(getResources(), R.drawable.rotated);

    Matrix matrix = new Matrix();
    matrix.postRotate(45);

    Bitmap rot = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(), myImg.getHeight(),
            matrix, true);

    circle.setImageBitmap(rot);        
}

所以,我基本上需要红色/绿色圆圈边缘才能到达屏幕边缘。这是否可以通过 imageView 实现,还是我需要编写自定义视图以允许内容脱离屏幕?顺便说一句,我实际上不会画整个圆圈,这只是一个解决我的问题的例子。

【问题讨论】:

    标签: android bitmap matrix android-imageview


    【解决方案1】:

    您必须计算实际的新宽度和高度。 尝试使用一些三角函数

    newHeight = height/sin(alpha),其中 alpha 是您的旋转角度...

    newWidth = width/cos(alpha)
    

    然后:

    Bitmap rot = Bitmap.createBitmap(myImg, 0, 0, newWidth, newHeight ,
                matrix, true);
    

    不确定计算,我没有检查,但我认为它是正确的,无论如何,这是一个很好的提示;)

    【讨论】:

    • 我原来是这么想的。唯一的问题是,当我传递给 createBitmap() 的大小比容器的宽度大时,它会强制关闭。
    • 它挂在 createBitmap() 或尝试将其放入 imageView 时?
    • 它在尝试将新的位图放入 ImageView 时强制关闭。创建一个更大的图像,裁剪它,然后将其添加到 imageView(具有正确的边界)会更好吗?
    • 我会接受这个答案。下面的一个是正确的,但你们两个基本上都有相同的答案。我想我更喜欢这个实现。谢谢!如果您可以在答案中添加“基于比例裁剪最终图像”,以便未来的人们可以看到它,那就太好了:)
    • @Rotemmiz 我试过你的旋转位图代码,很好,但是每次旋转我都会失去图像的清晰度。请给我建议......
    【解决方案2】:

    不确定它是否是最佳的,但它可以工作:只需将旋转的位图裁剪为初始大小。

    circle = (ImageView) findViewById(R.id.imageView1);
    Bitmap myImg = BitmapFactory.decodeResource(getResources(), R.drawable.rotated);
    
    Matrix matrix = new Matrix();
    matrix.postRotate(45);
    
    Bitmap rot = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(), myImg.getHeight(), matrix, true);
    
    int off = (rot.getWidth() - myImg.getWidth()) / 2;
    Bitmap result = Bitmap.createBitmap(rot, off, off, myImg.getWidth(), myImg.getHeight());
    
    circle.setImageBitmap(result);
    

    【讨论】:

      猜你喜欢
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2015-03-01
      • 1970-01-01
      相关资源
      最近更新 更多