gpt4 book ai didi

image - Unity UI以编程方式添加图像

转载 作者:行者123 更新时间:2023-12-05 03:06:16 25 4
gpt4 key购买 nike

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

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 () {

}
}

最佳答案

必须先设置parent,再设置position/rotation/scale!

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);
}

关于image - Unity UI以编程方式添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49604931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com