温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - UI.Image.pixelsPerUnitMultiplier doesn't update via code
c# image pixel unity3d user-interface

c# - UI.Image.pixelsPerUnitMultiplier不会通过代码更新

发布于 2020-04-06 00:14:09

我正在制作一个神经网络建模程序,并且已经为背景网格制作了平铺的图像。

我正在尝试通过代码更改每单位乘数的图像像素,这不起作用(在运行时通过编辑器进行编辑就可以了)

这是我的放大/缩小代码:

float desiredSize = this.GetComponent<Camera>().orthographicSize;
desiredSize -= Input.mouseScrollDelta.y * 3;

//Clamp between min and max
desiredSize = Mathf.Clamp(desiredSize, minSize, maxSize);

//Smoothly interpolates to desired size
this.GetComponent<Camera>().orthographicSize = Mathf.Lerp(this.GetComponent<Camera>().orthographicSize, desiredSize, 5f * Time.deltaTime);

//Change pixels per unit multiplier to half of camera's size (with only 1 decimal char)
gridImage.pixelsPerUnitMultiplier = Mathf.Round( (this.GetComponent<Camera>().orthographicSize / 2) * 10f) / 10f;

它按预期更改了每单位像素的值,但似乎对图像本身没有任何影响。

查看更多

提问者
Thiago
被浏览
177
derHugo 2019-08-29 11:12

有趣的是,此属性在任何地方都没有记录。我甚至没有发现它的源代码ImageEditor,也不是GraphcisEditor又那么现在我在什么是显示这一领域的实际负责真正感兴趣的^^

但是我发现,在更改了大小设置之后,编辑器会调用EditorUtility.SetDirty(graphic);当然,这在构建中不可用,但它使我寻找-我认为-正确的解决方案:

更改属性后,您必须致电 SetVerticesDirty

gridImage.SetVerticesDirty();

或简单地 SetAllDirty

gridImage.SetAllDirty();

在此处输入图片说明


我不确定效率,但是您可能仅在值实际更改时才调用它。

同时避免所有这些重复的GetComponent呼叫!一次执行一次,Awake然后重新使用参考。

最后,当前您Lerp是无用的!由于您获得了当前尺寸并在该尺寸上计算出所需的尺寸,因此根本不会进行平滑缩放。而是在类中使用全局字段并更新该字段:

// would even be better if you can already reference this in the Inspector
[SerializeField] private Camera _camera;

public Image gridImage;

public float minSize;
public float maxSize;

private float desiredSize;

private void Awake()
{
    if (!_camera) _camera = GetComponent<Camera>();

    // initialize the desired size with the current one
    desiredSize = Mathf.Clamp(_camera.orthographicSize, minSize, maxSize);

    // do it once on game start
    UpdateImage(desiredSize);
}

// Update is called once per frame
private void Update()
{
    var currentSize = _camera.orthographicSize;
    desiredSize -= Input.mouseScrollDelta.y * 3;

    //Clamp between min and max
    desiredSize = Mathf.Clamp(desiredSize, minSize, maxSize);

    // is the scaling already done?
    // -> Skip unnecessary changes/updates
    if (Mathf.Approximately(desiredSize, currentSize)) return;

    //Smoothly interpolates to desired size
    _camera.orthographicSize = Mathf.Lerp(currentSize, desiredSize, 5f * Time.deltaTime);

    UpdateImage(_camera.orthographicSize);
}

private void UpdateImage(float size)
{
    //Change pixels per unit multiplier to half of camera's size (with only 1 decimal char)
    gridImage.pixelsPerUnitMultiplier = Mathf.Round(size / 2 * 10f) / 10f;

    gridImage.SetVerticesDirty();
}

固定版本:

在此处输入图片说明

在分配“动画”时,“动画”末尾的轻微抖动来自您的舍入,pixelsPerUnitMultiplier您可能要考虑删除此舍入并直接应用

gridImage.pixelsPerUnitMultiplier = size / 2f