简体   繁体   English

Android:使用背景图像缩放按钮

[英]Android: scaling a button with a background image

I'm probably just being daft but my Google searches are not working out well. 我可能只是愚蠢但我的Google搜索效果不佳。

I have a bunch of buttons i add in code that all have dynamic text. 我在代码中添加了一堆按钮,这些按钮都有动态文本。 I've set a background image for each of these buttons since the default greybutton doesn't work well for my application. 我为每个按钮设置了一个背景图像,因为默认的灰色按钮对我的应用程序不起作用。

This works perfectly and when the text size (or content) changes, the button automatically grows to accommodate the expanded text. 这非常有效,当文本大小(或内容)发生变化时,按钮会自动增长以适应扩展文本。 What doesn't work is that I'd like the button to scale proportionally - ie if the background image is round, i'd like it to stay round rather than oval as the button gets bigger. 什么不起作用是我希望按钮按比例缩放 - 即如果背景图像是圆形的,我希望它保持圆形而不是椭圆形,因为按钮变大。

With an imagebutton, there is a property "Adjust view bounds" that does exactly this but I cant put text on an imagebutton. 使用图像按钮,有一个属性“调整视图边界”,它正是这样做但我不能将文本放在图像按钮上。 Is there something equivalent for a regular button? 有没有相当于常规按钮的东西?

or am I going about this wrong? 或者我错了吗?

i also tried setting the width of the button in code, but I can't seem to determine the new height (button.getHeight() returns 0) 我也尝试在代码中设置按钮的宽度,但我似乎无法确定新的高度(button.getHeight()返回0)

ok i found one way to do it... I modified the patch-9 to have its expandable area be the maximum on both axis. 好吧,我发现了一种方法...我修改了补丁-9,使其可扩展区域在两个轴上都是最大的。

then used the DisplayMetrics like this: 然后像这样使用DisplayMetrics:

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        buttonView.setGravity(Gravity.CENTER);

        int buttonSize=(int) Math.floor(metrics.density*1.6*fontSize);
        buttonView.setWidth(buttonSize);
        buttonView.setHeight(buttonSize);

where fontSize is the size of the font in DIP that i'm placing on each button. 其中fontSize是DIP中我放在每个按钮上的字体大小。 In this case, since I only have a single letter on each button, i don't need to worry about the text length, but one could obviously tweak this to handle that situation as well. 在这种情况下,因为我每个按钮上只有一个字母,所以我不需要担心文本长度,但是显然可以调整它来处理这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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