我必须以编程方式将 ImageView 添加到 RelativeLayout,使其在中心右侧 100dp。我为特定的屏幕尺寸和分辨率做了这个,但我希望它适用于任何尺寸的手机和密度。我为此尝试如下:
代码 :
float xCord, yCord;
float xCenter, yCenter;
float radius;
float angle;
double x, y;
TextView tv;
RelativeLayout container;
ImageView view;
RelativeLayout.LayoutParams viewParams;
DisplayMetrics metrics ;
float density;
int dps,pxs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_circular_animation);
metrics = getApplicationContext().getResources().getDisplayMetrics();
float width = metrics.widthPixels;
float height = metrics.heightPixels;
tv = (TextView)findViewById(R.id.tv);
container = (RelativeLayout)findViewById(R.id.container);
xCenter = convertToDP(width)/2;
yCenter = convertToDP(height)/2;
radius = 100;
angle = 0;
x = xCenter + radius * Math.cos(angle * Math.PI / 180);
y = yCenter + radius * Math.sin(angle * Math.PI / 180);
view = new ImageView(this);
viewParams = new RelativeLayout.LayoutParams(50,50);
viewParams.leftMargin = (int) x;
viewParams.topMargin = (int) y;
view.setLayoutParams(viewParams);
view.setImageResource(R.drawable.square);
container.addView(view);
tv.setText(String.valueOf(xCenter) + " " + String.valueOf(yCenter));
}
public int convertToDP(float px) {
density = getApplicationContext().getResources().getDisplayMetrics().density;
dps = (int) ((px/density) + 0.5f);
return dps;
}
}
我所做的是,获取屏幕尺寸和密度,然后将其除以 2 以获得中心线。一旦我有了绳子,我就使用公式在 0 度的圆周上得到点,但我没有得到正确的点。任何帮助都会很棒。