• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by qvatra · Apr 12, 2014 at 10:32 PM · rotationtexture2dmatrixgetpixelsrelative rotation

rotate an image by modifying Texture2D.GetPixels32() array

Is there build in function or any code sample that allows to transform Texture2D.GetPixels32() array in such way that output array would correspond to the same image which was rotated around its center by a specific angle?

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Apr 12, 2014 at 11:18 PM 0
Share

There's no Unity functions for rotating an image, and I'm not aware of code for this functionality. If performance was not an issue, it would be pretty easy to write this functionality using Texture2D.GetPixelBilinear(). Note that as with rotating an rectangular image in Photoshop, there are areas of the new image that will not have source pixels, and there will be source pixels that will not be included in the destination image (given the destination image is the same size). Also it would not be that hard to write your own Bilinear() function using the data from GetPixels32().

3 Replies

· Add your reply
  • Sort: 
avatar image
4
Best Answer

Answer by qvatra · Apr 14, 2014 at 09:27 PM

finally I've end up with this:

 #pragma strict
 
 var texToDraw : Texture2D;
 var x: int;
 var y: int;
 private var pix1:Color32[];
 private var pix2:Color32[];
 private var pix3:Color32[];
 var angle: int;
 
 function Start (){
         var background : Texture2D = Instantiate(renderer.material.mainTexture);
         pix1 = background.GetPixels32();
         pix2 = texToDraw.GetPixels32();
         var W = texToDraw.width;
         var H = texToDraw.height;
         
 
         
         pix3 = rotateSquare(pix2, Mathf.Deg2Rad*angle);
         
         for (var j = 0; j < H; j++){
             for (var i = 0; i < W; i++) {
                 //pix1[background.width/2 - texToDraw.width/2 + x + i + background.width*(background.height/2-texToDraw.height/2+j+y)] = pix2[i + j*texToDraw.width];
                 pix1[background.width/2 - W/2 + x + i + background.width*(background.height/2-H/2+j+y)] = pix3[i + j*W];
                 
             }
         }
         
         background.SetPixels32(pix1);
         background.Apply();
         renderer.material.mainTexture = background;
 }
 
 function rotateSquare(arr:Color32[], phi:float){
     var x:int;
     var y:int;
     var i:int;
     var j:int;
     var sn:float = Mathf.Sin(phi);
     var cs:float = Mathf.Cos(phi);
     var texture: Texture2D = Instantiate(texToDraw);
     var arr2:Color32[] = texture.GetPixels32();
     var W:int = texture.width;
     var H:int = texture.height;
     var xc: int = W/2;
     var yc: int = H/2;
     
     for (j=0; j<H; j++){
         for (i=0; i<W; i++){
           arr2[j*W+i] = new Color32(0,0,0,0);
           
           x = cs*(i-xc)+sn*(j-yc)+xc;
           y = -sn*(i-xc)+cs*(j-yc)+yc;
           
           if ((x>-1) && (x<W) &&(y>-1) && (y<H)){ 
               arr2[j*W+i]=arr[y*W+x];
           }
         }
     }
     return arr2;
 }
Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Apr 14, 2014 at 09:50 PM 0
Share

So you are picking the closest pixel and not generating an interpolated color? I assume the color is close enough?

avatar image qvatra · Apr 15, 2014 at 12:09 PM 0
Share

What do you mean by closest pixel? I'm using rotation matrix and translation here to find the exact coordinates for each color pixel. Off-course new coordinates are not always integers so I had to round them... but for the one time rotation the quality is still very good.

avatar image Mangas · Jan 23, 2015 at 09:10 AM 0
Share

qvatra would you be so kind as to explain the calculations made in the script?

I kind of need this. I'm rotating a texture inside a Sprite so the rotations in pixel art look as they should, basically defor$$anonymous$$g themselves while rotating, and I would really like to know what's exactly happening in these sentences:

 x = cs*(i-xc)+sn*(j-yc)+xc;
 y = -sn*(i-xc)+cs*(j-yc)+yc;

What's the meaning of xc and yc? Why are you doing (i - xc) and (j - yc)? I suppose you're using a rotation matrix to do the calculations, but I think I'm still missing something.

Also, I assume X and Y are some kind of offset in the script, though I'm not sure. And the last question, could you explain the math behind this sentence:

pix1[background.width/2 - W/2 + x + i + background.width*(background.height/2-H/2+j+y)] = pix3[i + j*W];

I understand pix3[i + j * W] is the way you run through the whole array, but the left operator is escaping me.

avatar image Benjamin_Philipp · Nov 05, 2016 at 06:48 AM 0
Share

Nice, this works! (well, I tried BeauWorlds' c# solution, to be perfectly accurate)

I assume this was written for cases where the output image is supposed to have the same dimensions as the input, since it appears to crop the corners that would lie outside the resulting edges.

It'll take me some time to pick the code apart to provide a solution where the resulting Texture2D will accommodate the rotated corners as well

avatar image
4

Answer by BeauWorlds · Oct 05, 2016 at 03:18 PM

An excellent answer to your own question! Thank you very much qvarta, you ended a long search for me ! I'm posting this as an answer juste to include a C# version for fellow c# devs! (also I've replaced the floats with doubles and Mathf with System.Math, it improves the accuracy)

using System;

public class ImageRotator {

     public static Texture2D RotateImage(Texture2D originTexture, int angle){
         Texture2D result;

         result = new Texture2D(originTexture.width, originTexture.height);

         Color32[] pix1 = result.GetPixels32();
         Color32[] pix2 = originTexture.GetPixels32();
         int W = originTexture.width;
         int H = originTexture.height;

         int x = 0;
         int y = 0;

         Color32[] pix3 = rotateSquare(pix2, (Math.PI/180*(double)angle), originTexture);

         for (int j = 0; j < H; j++){
             for (var i = 0; i < W; i++) {
                 //pix1[result.width/2 - originTexture.width/2 + x + i + result.width*(result.height/2-originTexture.height/2+j+y)] = pix2[i + j*originTexture.width];
                 pix1[result.width/2 - W/2 + x + i + result.width*(result.height/2-H/2+j+y)] = pix3[i + j*W];

             }
         }

         result.SetPixels32(pix1);
         result.Apply();

         return result;
     }

     static Color32[] rotateSquare(Color32[] arr, double phi, Texture2D originTexture){
         int x;
         int y;
         int i;
         int j;

         double sn = Math.Sin(phi);
         double cs = Math.Cos(phi);
         Color32[] arr2 = originTexture.GetPixels32();
         int W = originTexture.width;
         int H = originTexture.height;
         int xc = W/2;
         int yc = H/2;

         for (j=0; j<H; j++){
             for (i=0; i<W; i++){
                 arr2[j*W+i] = new Color32(0,0,0,0);

                 x = (int)(cs*(i-xc)+sn*(j-yc)+xc);
                 y = (int)(-sn*(i-xc)+cs*(j-yc)+yc);

                 if ((x>-1) && (x<W) &&(y>-1) && (y<H)){ 
                     arr2[j*W+i]=arr[y*W+x];
                 }
             }
         }
         return arr2;
     }
 }


Hope this can help someone, thanks again qvatra !

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image vonbetelgeuse · Jul 13, 2018 at 02:24 PM 0
Share

Could you help me with elaborating how to use this please?

I'm unfamiliar with how to use public static Texture2D, I have tried using

RotateImage(texName, 45);

but nothing appears to happen.

avatar image unityfearless · Dec 10, 2020 at 06:36 PM 0
Share

Thank for great post and effort. However the image rotate and then mirror also in c# code.

avatar image OnatKorucu · May 19, 2021 at 02:37 PM 0
Share

Thank you so much, it helped me greatly in my thesis project. But I am not sure how this works. Can you explain it a little bit maybe?

avatar image
0

Answer by shakerx3 · 2 days ago

IMPORTANT PLEASE READ!!! You don't understand the code? No surprise...

Maybe the author wants to have his fingerprint in your programs or just likes to be the only one who understands this code. I got the impression the answer is simply to confuse you. You need examples? Besides using nonsense variable names, here some obvious trolls:

  • result.width == originTexture.width == W

  • x = y = 0

  • Thus the line: pix1[result.width/2 - W/2 + x + i + result.width*(result.height/2-H/2+j+y)] = pix3[i + j*W] is the same as pix1[i + j*W] = pix3[i + j*W].

  • Why this random calculation then? And why would you bring in two variables (x and y) that are simply 0 and do add nothing to the calculation? Yep, he definitely tries to help you. But this is not even the worst. The whole method Start/RotateImage is redundant. You do not need to iterate over the pix[3] array. All you need is the function rotateSquare and perform result.SetPixels32(arr2) and you are done.

Yes this is btw the same method the author used at some other point, strange he didn't just use it, huh?


How it works: Basically a pixel rotation (see rotateSquare-method) is applied and this is no magic, its basic maths and it is nothing he came up with on his own:

  • y' = y*cos(a) - x*sin(a)

  • x' = y*sin(a) + x*cos(a)

(https://stackoverflow.com/questions/20104611/find-new-coordinates-of-a-point-after-rotation)

The rest besides this formulae is not relevant. So here is the readable and performant solution to the problem, hope this helps some people...

 public Texture2D RotateImage(Texture2D originTexture, float angle)
     {
         int oldX;
         int oldY;
         int width = originTexture.width;
         int height = originTexture.height;
         
         Color32[] originPixels = originTexture.GetPixels32();
         Color32[] transformedPixels = originTexture.GetPixels32();
         float phi = Mathf.Deg2Rad * angle;
 
         for (int newY = 0; newY < height; newY++)
         {
             for (int newX = 0; newX < width; newX++)
             {
                 transformedPixels[newY * width + newX] = new Color32(0, 0, 0, 0);
                 int newXNormToCenter = newX - width / 2;
                 int newYNormToCenter = newY - height / 2;
                 oldX = (int)(Mathf.Cos(phi) * newXNormToCenter + Mathf.Sin(phi) * newYNormToCenter + width / 2);
                 oldY = (int)(-Mathf.Sin(phi) * newXNormToCenter + Mathf.Cos(phi) * newYNormToCenter + height / 2);
                 bool InsideImageBounds = (oldX > -1) && (oldX < width) && (oldY > -1) && (oldY < height);
 
                 if (InsideImageBounds)
                 {
                     transformedPixels[newY * width + newX] = originPixels[oldY * width + oldX];
                 }
             }
         }
  
         Texture2D result = new Texture2D(width, height);
         result.SetPixels32(rotatedPixels);
 
         result.Apply();
         return result;
     }






Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

27 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Rotate cube non-relative to current rotation. 1 Answer

How to rotatate an array of points(x,z) around origin point(x,z)? 1 Answer

Texture rotation by renderer.material.SetMatrix 1 Answer

GetPixels() skews DXT5 compressed Texture2D 0 Answers

How to Decompose a TRS Matrix? 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges