Android 如何使用不同的屏幕分辨率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21369067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:26:21  来源:igfitidea点击:

How to Work With Different Screen Resolutions

androidiosunity3dscreen-resolution

提问by Ashish Beuwria

I'm using Unity 4.3.3 for my game. I'm making a game for Android and iOS devices. Since I'm pretty new to unity, I can't seem to find a way to work with different screen resolution. I'm using c# for my scripts.

我的游戏使用 Unity 4.3.3。我正在为 Android 和 iOS 设备制作游戏。由于我对统一还很陌生,我似乎无法找到一种使用不同屏幕分辨率的方法。我在我的脚本中使用 c#。

I want my game to run full screen. I've tested it on iPad 2 and it runs perfect but for iPhone 4 the sides are clipped and for iPhone 5 they are clipped even more. What is the solution? Which option should I choose under Player Settings > iOS > OtherSettings > Target Resolution?

我想让我的游戏全屏运行。我已经在 iPad 2 上测试过它,它运行得很好,但对于 iPhone 4,侧面被剪掉了,而对于 iPhone 5,它们被剪得更多。解决办法是什么?我应该在播放器设置 > iOS > 其他设置 > 目标分辨率下选择哪个选项?

回答by Steven Mills

unity changes its ingame camera to match the dimensions of the aspect ratio of the screen it's using. Obviously this isn't always desired, so there's a couple of ways around this:

unity 更改其游戏中的相机以匹配其使用的屏幕纵横比的尺寸。显然这并不总是需要的,所以有几种方法可以解决这个问题:

1) First method is very easy to implement, though it rarely looks good. You can simply change the camera's aspect ratio to match the one you've designed your game around. So if for example you've designed your game at 4:3, you'd do something like this:

1) 第一种方法很容易实现,虽然它很少看起来很好。您可以简单地更改相机的纵横比以匹配您设计游戏的纵横比。因此,例如,如果您以 4:3 的比例设计游戏,您将执行以下操作:

Camera.aspect = 4f/3f;

Just keep in mind that this will distort the game on different aspect ratios.

请记住,这会在不同的纵横比上扭曲游戏。

2) The other method is a little more complex, but the result looks much better. If you're using an orthographic camera, one important thing to keep in mind is that regardless of what screen resolution is being used, the orthographic camera keeps the height at a set value and only changes the width. For example, with an orthographic camera at a size of 10, the height will be set to 2. With this in mind what you'd need to do is compensate for the widest possible camera within each level (for example, have a wider background) or dynamically change the Orthographic Size of the camera until its width matches what you've created.

2)另一种方法稍微复杂一点,但结果看起来好多了。如果您使用的是正交相机,要记住的一件重要事情是,无论使用什么屏幕分辨率,正交相机都会将高度保持在一个设定值,而只会改变宽度。例如,对于大小为 10 的正交相机,高度将设置为 2。考虑到这一点,您需要做的是补偿每个级别内可能最宽的相机(例如,具有更宽的背景) 或动态更改相机的正交尺寸,直到其宽度与您创建的宽度相匹配。

GUI components are easier to implement simply by setting their position to depend on the screen resolution wherever needed. For example if you want a button to appear in the top right corner, you simply set its position to something like position = new Vector2(Screen.width - 50, 50);

GUI 组件更容易实现,只需将它们的位置设置为依赖于任何需要的屏幕分辨率。例如,如果您希望一个按钮出现在右上角,您只需将其位置设置为类似position = new Vector2(Screen.width - 50, 50);

EDIT: Since you mentioned devices you used, I did a bit of looking up to find what aspect ratio each one uses: Ipad2 = 4:3 , Iphone4 = 3:2, and Iphone5 = 16:9

编辑:既然你提到了你使用的设备,我做了一些查找以找到每个使用的纵横比: Ipad2 = 4:3 , Iphone4 = 3:2, and Iphone5 = 16:9

Since you said it looks perfect on the Ipad2, I'm guessing you've designed your game to use a 4:3 aspect ratio, so the "clipping" you mention is just that your orthographic camera has widened. The solution is to use one of the two methods I described above.

既然你说它在 Ipad2 上看起来很完美,我猜你已经将你的游戏设计为使用 4:3 的纵横比,所以你提到的“剪辑”只是你的正交相机已经加宽了。解决方案是使用我上面描述的两种方法之一。

You can see how it will look on each device within the unity editor fairly easily. If you go to the game tab (what pops up when you press play in the unity editor), you'll see it has a device name, along with a resolution and aspect ratio. Changing this will let you see what it will look like at different aspect ratios.

您可以很容易地看到它在统一编辑器中的每个设备上的外观。如果您转到游戏选项卡(在 Unity 编辑器中按播放时弹出的内容),您会看到它有一个设备名称,以及分辨率和纵横比。更改此设置将使您看到在不同纵横比下的外观。

回答by KennethLJJ

You may want to try capturing the device resolution by using Camera.ScreenWidth and Camera.ScreenHeight.

您可能想尝试使用 Camera.ScreenWidth 和 Camera.ScreenHeight 来捕获设备分辨率。

Then do some math to calculate the difference from the resolution you have and apply it to the parent object.

然后做一些数学运算来计算与您拥有的分辨率的差异并将其应用于父对象。

This will scale everything bigger/smaller to fit the device resolution without having multiple image resolutions etc for different resolution devices.

这将放大/缩小所有内容以适应设备分辨率,而无需针对不同分辨率设备设置多个图像分辨率等。

回答by SylafrsOne

If your goal is to get the previous width:

如果您的目标是获得先前的宽度:

[RequireComponent(typeof(Camera))]
public class ResizeCamera : MonoBehaviour 
{
    private float   DesignOrthographicSize;
    private float   DesignAspect;
    private float   DesignWidth;

    public  float   DesignAspectHeight;
    public  float   DesignAspectWidth;

    public void Awake()
    {
        this.DesignOrthographicSize = this.camera.orthographicSize;
        this.DesignAspect = this.DesignAspectHeight / this.DesignAspectWidth;
        this.DesignWidth = this.DesignOrthographicSize * this.DesignAspect;

        this.Resize();
    }

    public void Resize()
    {       
        float wantedSize = this.DesignWidth / this.camera.aspect;
        this.camera.orthographicSize = Mathf.Max(wantedSize, 
            this.DesignOrthographicSize);
    }
}

回答by Apurva

You need to change camera viewport according to device's aspect ratio. Suppose you made the game for 720x1080

您需要根据设备的纵横比更改相机视口。假设你制作了 720x1080 的游戏

Then in the script you should do

然后在脚本中你应该做

float xFactor = Screen.width / 720f;
float yFactor = Screen.height  / 1080f;

Camera.main.rect = new Rect(0,0,1,xFactor/yFactor);

Or

或者

The another way is, if you are making a game for aspect ratio 9:16 then

另一种方式是,如果您正在制作纵横比为 9:16 的游戏,那么

Do this in your script,

在您的脚本中执行此操作,

public float targetRatio = 9f/16f; //The aspect ratio of your game
void Start()
{
    Camera cam = GetComponent<Camera>();
    cam.aspect = targetRatio;
}

回答by user3234091

The easiest way I've solved this was as pointed out by Steven, force my perspective camera aspect ratio to the one I develop for. Of course this deforms some objects if the aspect ration I developed for is to different from the one of the device. For UI objects, if you are using the build-in, I create the rectangles based on a percent of whatever the screen size is

我解决这个问题的最简单方法是史蒂文指出的,强制我的透视相机纵横比为我开发的。当然,如果我开发的纵横比与设备的纵横比不同,这会使某些物体变形。对于 UI 对象,如果您使用内置功能,我会根据屏幕尺寸的百分比创建矩形

Rect(0.5 * Screen.width, 0.5 * Screen.height, 0.25 * Screen.width, 0.25 * Screen.height) 

That will place the top left corner at the center of the screen and create a rectangle of 1/4 the height and 1/4 the width of the screen. I'm using NGUI 2.7 for the UI and I haven't seen any issues with different aspect ratios so far, and that one uses an orthographic camera to render the UI

这会将左上角放在屏幕的中心,并创建一个 1/4 高度和 1/4 屏幕宽度的矩形。我在 UI 中使用 NGUI 2.7,到目前为止我还没有看到任何不同纵横比的问题,而且那个使用正交相机来渲染 UI

回答by DominoOne

I know it's an old thread, but people might still end up looking for an answer.

我知道这是一个旧线程,但人们最终可能仍在寻找答案。

To adjust a perspective camera to different screen aspect ratios with different behaviour than the Unity default, you need some trigonometry. All the necessary info about that is here: https://en.wikipedia.org/wiki/Angle_of_view

要将透视相机调整为具有不同于 Unity 默认行为的不同屏幕纵横比,您需要一些三角学。所有必要的信息都在这里:https: //en.wikipedia.org/wiki/Angle_of_view

If you want an easy way out, though, here's a solution that works with all camera types: http://u3d.as/oUX

但是,如果您想要一个简单的方法,这里有一个适用于所有相机类型的解决方案:http: //u3d.as/oUX

回答by Semimono

Ok, this is a big question. Many people have referred to forcing an aspect ratio, which is a good solution to consider. However for many games this is not appropriate. For many game designs, you want the game to feel like it's native to the device/screen it's running on, and you want to use every square inch of screen real-estate you can. To do this, you must build and test every system in your game for different sized and shaped screens. It's a very similar problem to building apps and websites for multiple devices.

好吧,这是一个很大的问题。很多人都提到了强制纵横比,这是一个很好的解决方案。然而,对于许多游戏来说,这是不合适的。对于许多游戏设计,您希望游戏感觉就像它是运行它的设备/屏幕的本机一样,并且您希望尽可能使用每一平方英寸的屏幕空间。为此,您必须针对不同大小和形状的屏幕构建和测试游戏中的每个系统。为多个设备构建应用程序和网站是一个非常相似的问题。

Screen Size

屏幕尺寸

The screen size can be retrieved programmatically using the DPIand the resolutionwith a statement such as:

可以使用DPI分辨率通过以下语句以编程方式检索屏幕大小:

Resolution res = Screen.currentResolution;
float screenSquareInches = res.width * res.height / Screen.dpi;

For the content on the screen that is viewed through the camera, there's only one variable that needs to be scaled, and that's the size of the camera (or how much stuff in the game world that will be squeezed onto the screen). You can control the size of the camera with the field of viewfor 3D games or the orthographic sizefor 2D games. Only testing will say what equation supports the widest range of screen sizes, but something along these lines could serve well:

对于通过摄像头查看的屏幕内容,只有一个变量需要缩放,那就是摄像头的大小(或者游戏世界中有多少东西会被挤压到屏幕上)。您可以通过3D 游戏的视野或2D 游戏的正交尺寸来控制相机的大小。只有测试才能说明什么方程式支持最广泛的屏幕尺寸,但这些方面的东西可以很好地发挥作用:

// this should be a tweakable number, so you can fine tune it to your needs. It represents the screen size at which the camera size should not be scaled at all
float expectedScreenArea = 20;
// this number should also be tweakable, which declares how much smaller/larger text can get depending on the screen size. Generally larger screens are viewed from farther away, so scaling should be slight
float cameraScalingRate = 0.25f;
// multiply this number by the default/base camera size you have picked, whether that's field of view or orthographic size
float cameraSizeMultiplier = 1 + (screenSquareInches / expectedScreenArea - 1) * cameraScalingRate;

Ok, that should get you most of the way on scaling the game world, but what about UI elements, things like text, HUD, and on-screen controls? Well, for elements like text, the above equation should work decently well, though you might want a different value for the scaling rate. For on screen controls, you might want a more full transformation, such as joysticks moving to the bottom corners of the screen on a tablet rather than centered on the sides, or if it's not a touch screen device, remove on-screen controls altogether. That's outside the scope of this question.

好的,这应该可以让您在扩展游戏世界方面获得大部分方法,但是 UI 元素、文本、HUD 和屏幕控制等内容呢?好吧,对于像文本这样的元素,上面的等式应该可以很好地工作,尽管您可能需要不同的缩放率值。对于屏幕控制,您可能需要更全面的转换,例如将操纵杆移动到平板电脑屏幕的底部角落而不是在两侧居中,或者如果它不是触摸屏设备,则完全删除屏幕控制。这超出了这个问题的范围。

Screen Aspect Ratio

屏幕纵横比

The aspect ratio of the screen (how wide vs. tall is it) is also important and needs it's own handling. Generally the best way to do this is to freeze the vertical height of the screen, so that as the screen gets wider, elements on the screen are not scaled, but as the screen gets taller, elements on the screen scale proportionally to how much taller the screen grows. This is already the default behavior for cameras, but for UI elements you have to set it as such. This is relatively easy if you are using the new UI system with canvas'. On a CanvasScalar component, there's a propertythat controls how the elements are scaled depending on the aspect ratio. Change this to match width or height, and have it match height.

屏幕的纵横比(多宽与多高)也很重要,需要自己处理。通常最好的方法是冻结屏幕的垂直高度,这样随着屏幕变宽,屏幕上的元素不会缩放,但随着屏幕变高,屏幕上的元素按比例缩放屏幕变大。这已经是相机的默认行为,但对于 UI 元素,您必须如此设置。如果您使用带有画布的新 UI 系统,这相对容易。在 CanvasScalar 组件上,有一个属性可以根据纵横比控制元素的缩放方式。更改它以匹配宽度或高度,并使其匹配高度。

For Further Consideration

供进一步考虑

With supporting different screen sizes and shapes there's more to consider than just making everything fit. You also need to make sure you game plays well on the different screens. This ranges from things as subtle as not making the player feel claustrophobic on a small screen to making sure enemies can't shoot at the player if they're off screen to making sure you update boundaries that keep elements on screen. Another thing to consider if this is a PC game is that someone might plug their computer into a different screen or change the resolution on the fly. With this in mind, it can be good to rerun the above equations as needed so a player doesn't have to exit the game to get things lining up right again.

通过支持不同的屏幕尺寸和形状,需要考虑的不仅仅是让一切都适合。您还需要确保您的游戏在不同的屏幕上都能正常运行。这包括一些微妙的事情,例如不会让玩家在小屏幕上感到幽闭恐惧症,到确保敌人在屏幕外时无法向玩家开枪,再到确保更新将元素保留在屏幕上的边界。如果这是 PC 游戏,需要考虑的另一件事是有人可能会将他们的计算机插入不同的屏幕或动态更改分辨率。考虑到这一点,根据需要重新运行上述等式可能会很好,这样玩家就不必退出游戏来让事情重新排列整齐。

回答by a_m_dev

if You have no choice You also can Do some more work and add a special Script to your camera that:

如果您别无选择,您还可以做更多的工作并为您的相机添加一个特殊的脚本:

  1. checks Screen Resolution for device
  2. sets the target resolution for that
  3. and also sets the target aspect ratio for that (IMPORTANT)
  1. 检查设备的屏幕分辨率
  2. 为此设置目标分辨率
  3. 并为此设置目标纵横比(重要)

all you need to do is just writing a base function for checking the screen resolution (both width and height for devices that you want) and then add some more functionality to that for setting the proper screen resolution and aspect ratio!

您需要做的就是编写一个基本函数来检查屏幕分辨率(您想要的设备的宽度和高度),然后添加一些更多的功能来设置正确的屏幕分辨率和纵横比!

回答by Mubasher Ikram

Its very easy for Unity Now as Unity3D has its own UI system. For 3D Unity Adjusts the camera Automatically with screen size. Problem arises for UI actually and its a little bit tricky. First of all try to figure out which elements needs to change position and size with screen size. For example if you have a button exactly in the center of screen. Then it doesnt need to change the position according to screen. It will remain in center.

因为 Unity3D 有自己的 UI 系统,所以现在对 Unity 来说非常容易。对于 3D Unity 根据屏幕大小自动调整相机。UI实际上出现了问题,它有点棘手。首先尝试找出哪些元素需要随着屏幕大小改变位置和大小。例如,如果您在屏幕中央有一个按钮。这样就不需要根据屏幕改变位置了。它将保持在中心。

Now lets take a scenario in which you have a button in the corner of screen like we see pause button in top right or top left. Now you will have to anchor your button in the corner accordingly. It doesnt matter on which screen size the game is running, the pause button should stick to the corner.

现在让我们假设您在屏幕的角落有一个按钮,就像我们在右上角或左上角看到暂停按钮一样。现在,您必须相应地将按钮锚定在角落。游戏运行的屏幕尺寸无关紧要,暂停按钮应该粘在角落里。

Now lets take another case in which you have a background in your menu. Now you will have to apply stretch for this BG sprite. This BG will be stretching and shrinking accordingly but all items on it will have a fix size. For this it is recommended to have BGs flat so that a same BG can have a good quality for 16:10 or 4:3 (Its all about Unity Native UI)

现在让我们再看看菜单中有背景的情况。现在你必须为这个 BG 精灵应用拉伸。此 BG 将相应地拉伸和收缩,但其上的所有项目都将具有固定大小。为此,建议将 BG 设为平坦,以便相同的 BG 在 16:10 或 4:3 时具有良好的质量(这完全是关于 Unity Native UI)

回答by Shubhra

If you are developing 2d game,that is your camera is in orthographic view then Just do the following code and attach it with your gameobject. It will scale the gameobject(in this case the sprite) with the screen resolution.

如果您正在开发 2d 游戏,即您的相机处于正交视图中,那么只需执行以下代码并将其附加到您的游戏对象中即可。它将使用屏幕分辨率缩放游戏对象(在本例中为精灵)。

void Resize()
{
    SpriteRenderer sr=GetComponent<SpriteRenderer>();
    if(sr==null) return;

    transform.localScale=new Vector3(1,1,1);

    float width=sr.sprite.bounds.size.x;
    float height=sr.sprite.bounds.size.y;


    float worldScreenHeight=Camera.main.orthographicSize*2f;
    float worldScreenWidth=worldScreenHeight/Screen.height*Screen.width;

    Vector3 xWidth = transform.localScale;
    xWidth.x=worldScreenWidth / width;
    transform.localScale=xWidth;

    Vector3 yHeight = transform.localScale;
    yHeight.y=worldScreenHeight / height;
    transform.localScale=yHeight;

}