问题描述
我将以下内容用作布局的背景:
I'm using the following as a background for a layout:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="20dip"/>
<padding android:left="0dip" android:top="0dip" android:right="0dip" android:bottom="0dip" />
</shape>
,但是在4"800x480屏幕上的圆角外观与在4.7" 1280x720屏幕上的圆角差异很大.有什么方法可以设置相对于屏幕的半径?
but the rounded-ness looks very different on a 4" 800x480 screen than it does on a 4.7" 1280x720 screen. Is there any way to set the radius relative to the screen?
推荐答案
一个好问题,我不知道一种使用XML的简洁方法(如果使用dip值不足的话),但是您可以通过编程方式创建可绘制对象并根据屏幕尺寸进行一些数学计算,以实现所需的结果.
A good question, I do not know of a neat way to do this with XML (if using dip values is insufficient), however you could create your drawable programmatically and do some math based on the screen size to achieve what you want.
// Create a drawable
GradientDrawable shape = new GradientDrawable();
// Get the screen size
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
// Do some math to get the radius value to scale
int radius = (int) Math.round(width * height / 100000);
// Set the corner radius
shape.setCornerRadius(radius);
// Apply shape as background
setBackground(shape);
因此,对于1280x800的屏幕,其宽度为*高度= 1024000除以100000舍入后得出的半径为10px.但是,在800x480屏幕上,半径将为4px.但是,这没有考虑屏幕的物理尺寸,因此,如果出现问题,您可以获取以英寸为单位的物理尺寸:
So for a 1280x800 screen this would be width * height = 1024000 divided by 100000 rounded gives you a 10px radius. However on a 800x480 screen the radius would be 4px. This doesn't take into account physical size of the screen however, so if this is an issue you can get the physical size in inches:
DisplayMetrics dm = new DisplayMetrics();
display.getMetrics(dm);
double x = Math.pow(dm.widthPixels/dm.xdpi,2);
double y = Math.pow(dm.heightPixels/dm.ydpi,2);
double inches = Math.sqrt(x+y);
然后您还可以将此值考虑在内,例如:
Then you can factor this value also, for example:
int radius = (int) Math.round(width * height * inches / 500000);
因此,对于1280x800 4屏幕,这将是宽度*高度* 4 = 4096000除以500000,四舍五入得到的半径为8px.在800x480 10"屏幕上,这将是宽度*高度* 10 = 4096000除以500000四舍五入,这也为您提供了8px的半径.
So now for a 1280x800 4" screen this would be width * height * 4 = 4096000 divided by 500000 rounded gives you an 8px radius. On a 800x480 10" screen this would be width * height * 10 = 4096000 divided by 500000 rounded which also gives you an 8px radius.
我知道这是一个肮脏的技巧,您可能需要调整数学以使其完美缩放,但是我相信这是可以实现缩放半径的唯一方法.
I know this is a dirty hack and you may need to tweak the math to get it to scale perfectly, but I believe this is the only way that scaling the radius can be achieved.
这篇关于Android布局-设置相对于屏幕尺寸的圆角半径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!