unity图片任意裁剪
时间: 2023-10-02 12:10:17 浏览: 75
Unity中可以使用Texture2D类来对图片进行任意裁剪。以下是一个简单的示例代码:
```csharp
// 加载图片
Texture2D originalTexture = Resources.Load<Texture2D>("Image");
// 设置裁剪区域
Rect rect = new Rect(10, 10, 100, 100);
// 裁剪图片
Texture2D croppedTexture = new Texture2D((int)rect.width, (int)rect.height);
croppedTexture.SetPixels(originalTexture.GetPixels((int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height));
croppedTexture.Apply();
// 显示裁剪后的图片
Sprite croppedSprite = Sprite.Create(croppedTexture, new Rect(0, 0, croppedTexture.width, croppedTexture.height), new Vector2(0.5f, 0.5f));
GameObject croppedImage = new GameObject("CroppedImage", typeof(RectTransform), typeof(Image));
croppedImage.GetComponent<Image>().sprite = croppedSprite;
```
在上面的示例中,首先使用Resources.Load方法加载图片。然后使用Rect类定义裁剪区域。接着使用Texture2D类的GetPixels方法获取裁剪区域内的像素,并使用SetPixels方法将像素设置到一个新的Texture2D对象中。最后使用Sprite.Create方法创建一个新的Sprite,并使用Image组件将其显示在界面上。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)