简体   繁体   中英

Android: ImageView Rotation Scale

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.

普通影像

图像旋转不正确,无论如何对我来说

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM