unity 图片旋转(180度翻转)

    //水平翻转
 	Texture2D HorizontalFlipTexture(Texture2D texture)
    {
        //得到图片的宽高
        int width = texture.width;
        int height = texture.height;

        Texture2D flipTexture = new Texture2D(width, height);

        for (int i = 0; i < width; i++)
        {
            flipTexture.SetPixels(i, 0, 1, height, texture.GetPixels(width - i - 1, 0, 1, height));
        }
        flipTexture.Apply();

        return flipTexture;
    }
    // 垂直翻转
 	Texture2D VerticalFlipTexture(Texture2D texture)
    {
        //得到图片的宽高
        int width = texture.width;
        int height = texture.height;

        Texture2D flipTexture = new Texture2D(width, height);
        for (int i = 0; i < height; i++)
        {
            flipTexture.SetPixels(0, i, width, 1, texture.GetPixels(0, height - i - 1, width, 1));
        }
        flipTexture.Apply();
        return flipTexture;
    }

GetPixel和SetPixel,GetPixel用来获取坐标为(x,y)的像素点的颜色,即参数为int x和int y,返回值为Color;SetPixel则用来设置新的像素点,参数为int x、int y及Color。一张2D Texture由width*height个像素点组成,想象一张网格图,每个网格对应一个像素点,则每个像素的横坐标在[0,width - 1]内,纵坐标在[0,height - 1]内。假设我们要将图片顺时针旋转90°,由于Unity中的坐标原点在图的左下角,故一个坐标为(x,y)的像素点旋转90°后的坐标变为了(y,width - 1 - x),对每个像素点进行这样的坐标变换就可实现图片的旋转了。具体代码如下:

public class TextureRotate
{
  Texture2D texture = new Texture2D(300, 400);
  int width = texture.width;  //图片原本的宽度
  int height = texture.height;  //图片原本的高度
  Texture2D newTexture = new Texture2D(height,width); //实例化一个新的texture,高度是原来的宽度,宽度是原来的高度
 
  public Texture2D rotate()
  {
    for (int i = 0; i < width - 1; i++) {
      for (int j = 0; j < height - 1; j++) {
        Color color = texture.GetPixel(i,j);
        newTexture.SetPixel(j, width - 1 - i, color);
      }
    }
    newTexture.Apply();
    return newTexture;
  }
}


 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rain_love_snow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值