[英]Java (Android): How to scale a drawable without Bitmap?
I need to scale the background image of a button but can't turn it into a Bitmap. 我需要缩放按钮的背景图像,但不能将其转换为位图。 Here is the code right now: 这是现在的代码:
int height = 50;
int width = 80;
Button b = new Button (this);
b. setBackgroundResource(R.drawable.btn);
Now I need to scale "R.drawable.btn" according to the "height" and "width". 现在我需要根据“高度”和“宽度”缩放“R.drawable.btn”。 The setBackgroundResource won't accept a Bitmap. setBackgroundResource不接受Bitmap。 How do I do that? 我怎么做?
Thank you. 谢谢。
You can allow the layout parameters to control the scale or you can scale the image yourself. 您可以允许布局参数控制比例,也可以自己缩放图像。
Allow the layout to scale the image: 允许布局缩放图像:
b.setBackground(getResources().getDrawable(R.drawable.btn));
Scale the image manually: 手动缩放图像:
Bitmap original = BitmapFactory.decodeResource(context.getResources(), R.drawable.btn);
Bitmap b = Bitmap.createScaledBitmap(original, width, height, false);
Drawable d = new BitmapDrawable(context.getResources(), b);
button.setBackground(d);
Warning : The image may not appear onscreen scaled exactly as you expect. 警告 :图像可能无法在屏幕上按预期缩放。 This is because depending on the layout parameters of your Button
, Android may additionally scale the image based on the hardware screen density of your device. 这是因为根据您的Button
的布局参数,Android可能会根据您设备的硬件屏幕密度另外缩放图像。
this will turn a bitmap into a drawable 这会将位图变成可绘制的
image = new BitmapDrawable(getResources(),MenuScreen.image1);
image is the drawable and image1 is the bitmap image是drawable,image1是bitmap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.