【问题标题】:Unity UI add Image programmaticallyUnity UI 以编程方式添加图像
【发布时间】:2018-04-02 03:27:30
【问题描述】:

我使用以下代码将图像添加到画布 但是图像位于左下角 我希望图像位于画布的中心 任何人都可以帮助我

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TestController : MonoBehaviour {

    public GameObject canvas;
    //public Sprite refSprite;

    // Use this for initialization
    void Start () {

        GameObject imgObject = new GameObject("testAAA");

        RectTransform trans = imgObject.AddComponent<RectTransform>();
        trans.anchoredPosition = new Vector2(0.5f, 0.5f);
        trans.localPosition = new Vector3(0, 0, 0);
        trans.position = new Vector3(0, 0, 0);


        Image image = imgObject.AddComponent<Image>();
        Texture2D tex = Resources.Load<Texture2D>("red");
        image.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
        imgObject.transform.SetParent(canvas.transform);


    }

    // Update is called once per frame
    void Update () {

    }
}

【问题讨论】:

    标签: image user-interface unity3d


    【解决方案1】:

    你必须先设置父级,然后设置位置/旋转/缩放!

    void Start () {
        GameObject imgObject = new GameObject("testAAA");
    
        RectTransform trans = imgObject.AddComponent<RectTransform>();
        trans.transform.SetParent(canvas.transform); // setting parent
        trans.localScale = Vector3.one;
        trans.anchoredPosition = new Vector2(0f, 0f); // setting position, will be on center
        trans.sizeDelta= new Vector2(150, 200); // custom size
    
        Image image = imgObject.AddComponent<Image>();
        Texture2D tex = Resources.Load<Texture2D>("red");
        image.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f));
        imgObject.transform.SetParent(canvas.transform);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多