我有5个变量。
位图宽度和高度。 屏幕宽度和高度。 所需的百分比
如何使用矩阵(即1.0正常,0.5半尺寸,2.0双倍尺寸)使位图成为所需的屏幕百分比。
位图是不同帧宽的精灵(I.E爆炸是200x4000(20帧200x200,而对象是65x195,因此如果有帮助则每个对象65x65)。
我的目标是将某些内容传递给ResizeBitmap,如(Bitmap,100),这将是100%的屏幕,同时保持宽高比。
所以ResizeBitmap(Bitmap,10)会占据屏幕的10%。
这是我到目前为止所得到的,它崩溃显示的是错误的尺寸。
public Bitmap ResizeBitmap(Bitmap bitmap, int screen_percentage)
{
float scale;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float percentage_of_screen;
float percentage_of_percentage_screen;
if(screen_width > screen_height)
{
percentage_of_screen = (screen_width / 100) * width;
percentage_of_percentage_screen = (screen_width / 100) * screen_percentage;
scale = percentage_of_screen / percentage_of_percentage_screen;
}
else
{
percentage_of_screen = (screen_height / 100) * height;
percentage_of_percentage_screen = (screen_height / 100) * screen_percentage;
scale = percentage_of_screen / percentage_of_percentage_screen;
}
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scale, scale);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
任何人都可以修复我的代码或至少帮助我,因为我浪费了太多时间在这个功能上。
感谢。
答案 0 :(得分:1)
测试:
public class StackOverflowActivity extends Activity{
private int screen_width;
private int screen_height;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// in main.xml use an ImageView with android:id="@+id/img"
ImageView view = (ImageView)findViewById(R.id.img);
// in your drawables folder, put an image named circle.png
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.circle);
Display display = getWindowManager().getDefaultDisplay();
screen_width = display.getWidth();
screen_height = display.getHeight();
Bitmap scale = resizeBitmap(bmp, 100);
view.setImageBitmap(scale);
}
public Bitmap resizeBitmap(Bitmap bitmap, int screen_percentage)
{
////////////// IMPORTANT ////////////////////
// Use '/ 100.0f' otherwise your percentage will be 0..
// this will later on, cause the newWidth & newHeight to be 0 as well
// which causes the app to crash
float percentage = screen_percentage / 100.0f;
float scale = screen_width / 100 * percentage;
if(screen_width < screen_height)
{
scale = screen_height / 100 * percentage;
}
int newWidth = (int) (bitmap.getWidth() * scale);
int newHeight = (int) (bitmap.getHeight() * scale);
if(newWidth <= 0 || newHeight <= 0)
{ // Extra check, for invalid width/height
Log.e("test", "invalid dimension ("+newWidth+"x"+newHeight+")");
return bitmap;
}
return Bitmap.createScaledBitmap (bitmap, newWidth, newHeight, true);
}
}
为了避免缩放比例问题,请在main.xml中使用它
<ImageView
android:id="@+id/img"
android:background="@null"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:scaleType="centerInside"/>