简体   繁体   English

Android以编程方式添加imageview修复所有屏幕的大小

[英]Android add imageview programmatically fix size all screen

I'm creating several ImageViews programmatically, but I'm running into an issue where there are different ImageView sizes on different displays. 我正在以编程方式创建多个ImageView,但我遇到了一个问题,即在不同的显示器上有不同的ImageView大小。 I want the ImageView size to be fixed on all screens. 我希望在所有屏幕上修复ImageView大小。 Here is how I am generating those ImageViews: 以下是我生成这些ImageView的方法:

for (int i = 0; i < myImageList.size(); i++) {
    ImageView iv = new ImageView(this);
    iv.setImageResource(myImageList.get(i));
    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(420, 210);
    lp.gravity = Gravity.CENTER;
    iv.setLayoutParams(lp);
    float angleDeg = i * 360.0f / myImageList.size() - 70.0f;
    float angleRad = (float) (angleDeg * Math.PI / 180.0f);
    iv.setTranslationX(320 * (float) Math.cos(angleRad));
    iv.setTranslationY(320 * (float) Math.sin(angleRad));
    iv.setRotation(angleDeg + 80.0f);
    main.addView(iv);
    final int finalI = i;
}

You could introduce new class derived from ImageView and make all those adjustments in that class. 您可以引入从ImageView派生的新类,并在该类中进行所有这些调整。 Then just replaces ImageView to your class implementation in layouts etc 然后只需将ImageView替换为布局等中的类实现

There are multiple interpretations of your questions. 您的问题有多种解释。

  1. The ImageView should have same size on all the devices - use dp . ImageView在所有设备上应该具有相同的大小 - 使用dp You are using pixels right now in the LayoutParams . 您现在正在LayoutParams中使用pixels
  2. The ImageView should look that it has same size on all screens - find the width and height of the screen, set an aspect ration, eg. ImageView应该看起来在所有屏幕上都有相同的大小 - 找到屏幕的宽度和高度,设置一个宽高比例,例如。 0.33 and use that factored width and height in LayoutParams . 0.33并在LayoutParams使用该因式宽度和高度。
  3. Use MATCH_PARENT in LayoutParams for width as well as height and the ImageView will take the full size (of the parent). 在LayoutParams中使用MATCH_PARENT获取宽度和高度,ImageView将采用(父级)的完整大小。

This question has a lot of great explanation about dp , px , sp that could be useful - What is the difference between "px", "dip", "dp" and "sp"? 这个问题对dppxsp有很多很好的解释,这可能有用 - “px”,“dip”,“dp”和“sp”之间有什么区别?

To find screen sizes 查找屏幕尺寸

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    // these are sizes in pixels
    metrics.widthPixels, metric.heightPixels

Then, you can use this 然后,你可以使用它

iv.setScaleType(ImageView.ScaleType.FIT_XY);

See this link for all ScaleType values 有关所有ScaleType值,请参阅此链接

Android ImageView ScaleType: A Visual Guide Android ImageView ScaleType:可视指南

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

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