Java 在Android上旋转图像而不收缩
我需要在我正在使用的应用程序上创建一个指南针。因此,我尝试创建一个名为CompassView的新视图,该视图基本上扩展了imageview,显示了一个指向东西南北的位图,使用传感器查找手机指向的角度,并相应地旋转图像,以便创建一个实际的罗盘。但问题是,如果我尝试将图像旋转到一些角度,比如45度,它会缩小。这里有一些图片可以更好地解释它 如你所见,当我试着旋转45度时,第二幅图像缩小了。我想让它做的是: 以下是我当前使用的代码:Java 在Android上旋转图像而不收缩,java,android,image,rotation,Java,Android,Image,Rotation,我需要在我正在使用的应用程序上创建一个指南针。因此,我尝试创建一个名为CompassView的新视图,该视图基本上扩展了imageview,显示了一个指向东西南北的位图,使用传感器查找手机指向的角度,并相应地旋转图像,以便创建一个实际的罗盘。但问题是,如果我尝试将图像旋转到一些角度,比如45度,它会缩小。这里有一些图片可以更好地解释它 如你所见,当我试着旋转45度时,第二幅图像缩小了。我想让它做的是: 以下是我当前使用的代码: Bitmap bMap = BitmapFac
Bitmap bMap = BitmapFactory.decodeResource(getResources(),
R.drawable.compass);
Matrix xMatrix = new Matrix();
xMatrix.reset();
xMatrix.postRotate(360-mValue, 75, 75); //This is 75 because 150 is the image width
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,
bMap.getWidth(), bMap.getHeight(), xMatrix, true);
setImageBitmap(bMapRotate);
任何帮助都将不胜感激。谢谢
编辑:(解决方案)
多亏了这个公认的答案,我终于让它工作起来了。下面是我为任何想知道它是如何工作的人使用的代码:
RotateAnimation rAnimAntiClockWise = new RotateAnimation(
360 - mValue, 360 - event.values[0],
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
//mValue is the angle in degrees and i subtracted it from 360 to make it anticlockwise, and event.values[0] is the same thing as mValue
rAnimAntiClockWise.setFillAfter(true);
rAnimAntiClockWise.setInterpolator(new LinearInterpolator());
rAnimAntiClockWise.setDuration(0);
startAnimation(rAnimAntiClockWise);
问题是你的新图像实际上更大了,因为源的角“突出”,所以视图会缩小以适应 一些可能的方法:
Bitmap.createBitmap(位图源,int x,int y,int width,int height)
,复制正确大小的中心区域。很容易给你的代码,但创建一个无用的中间位图bMapRotate = Bitmap.createBitmap(
bMap.getWidth(), bMap.getHeight(), bMap.getConfig());
Canvas canvasRotate = new Canvas(bMap);
canvasRotate.drawBitmap(bMap, xMatrix, paint); // any opaque Paint should do
您可以使用另一种技巧,其工作原理与旋转相同,并且不会调整图像大小。我实际上以45度角旋转图像,并在动画之后保持更改
rAnimAntiClockWise = new RotateAnimation(0.0f, 45.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rAnimAntiClockWise.setFillAfter(true);
rAnimAntiClockWise.setInterpolator(new LinearInterpolator());
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.rotate);
rAnimAntiClockWise.setDuration(100);
img_rotate.startAnimation(rAnimAntiClockWise);
谢谢你让我知道路。。我知道我的备选方案,但我只是不知道如何实现它们,因为我不熟悉画布和自定义视图。很多时候,我不知道这可以通过旋转动画实现。我只需要修改代码的某些部分就可以了