爪哇(安卓):如何缩放绘制无位图? [英] Java (Android): How to scale a drawable without Bitmap?

查看:126
本文介绍了爪哇(安卓):如何缩放绘制无位图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要扩展按钮的背景图片,但不能把它变成一个位图。这里是code现在:

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

现在我需要按照高度和宽度缩放R.drawable.btn。该setBackgroundResource不会接受一个位图。我该怎么办呢?

Now I need to scale "R.drawable.btn" according to the "height" and "width". The setBackgroundResource won't accept a Bitmap. How do I do that?

感谢你。

推荐答案

您可以允许布局参数来控制规模,或者您也可以自己将图像缩放。

You can allow the layout parameters to control the scale or you can scale the image yourself.

允许布局缩放图像:

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.

这篇关于爪哇(安卓):如何缩放绘制无位图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆