Android: ImageView Rotation Scale

2020-06-06 04:53发布

I have an imageView and I am basically trying to make a thermometer style gauge. I have added an image below for testing and I am basically trying to rotate the image. The first picture has the image in its standard layout. After trying to rotate the image, The width still fills the screen, but it scales the image down to make room for the corners, making the actual image appear smaller. I want the image to remain the exact same size, but rotate based on the Matrix passed to it.

Normal Image

Image rotated incorrectly, for me anyways

Here is the code I am using for the rotation:

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);        
}

So, I basically need the red/green circle edge to reach the edge of the screen. Is this possible with an imageView or will I need to write a custom view to allow stuff to be off screen? By the way, I am not actually gonna draw this whole circle, this is just an example to get my issue across.

2条回答
▲ chillily
2楼-- · 2020-06-06 05:12

Not sure that it is optimal but it work: just crop rotated bitmap to initial size.

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);
查看更多
Viruses.
3楼-- · 2020-06-06 05:17

You have to calculate the actual new width and height. try using some trigonometry

newHeight = height/sin(alpha), where alpha is your rotation angle...

newWidth = width/cos(alpha)

then :

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

not sure about the calculation, I didn't check it, but I think it correct, anyway, it's a great hint ;)

查看更多
登录 后发表回答