Search Unity

Copy a texture... but with another texture's alpha channel?

Discussion in 'Scripting' started by DanTaylor, Sep 22, 2014.

  1. DanTaylor

    DanTaylor

    Joined:
    Jul 6, 2013
    Posts:
    119
    Hello there.
    I was just wondering if it was possible to use something texture2d.readPixels to...
    • copy a texture to a new texture...
    • but take the alpha values from another texture
    Why do I want to do this? Well, I want to add round corners to user created images (such as photos and profile pics) so they fit nicely with my GUI style.

    Can it be done?
    And if so how? (A code snippet would be much appreciated!)

    Thanks,
    Dan
     
  2. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,717
    Yes, it can easily be done.

    What have you tried?
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    The easiest way to do this would be if you're on the 4.6 beta - you can create a mask and simply have the user image as its child.

    If you know shaders, it's almost as easy.

    You CAN create textures like that if you like, and it's reasonably straightforward, but it'll be kind of a pain and not very efficient.

    If the images are the same size, then something like this should work:
    Code (csharp):
    1.  
    2. Color[] pixelsColor = texture1.GetPixels();
    3. Color[] pixelsAlpha = texture2.GetPixels();
    4. Color[] resultingPixels = new Color[pixelsColor.Length];
    5. for (int c=0;c<pixelsColor.Length;c++) {
    6. resultingPixels[c] = new Color(pixelsColor[c].r, pixelsColor[c].g, pixelsColor[c].b, pixelsAlpha[c].a);
    7. }
    8. Texture2D result = new Texture2D(texture1.width, texture1.height);
    9. result.SetPixels(resultingPixels);
    10. result.Apply();
    11.  
     
    brokenm likes this.