Reputation: 6281
Hi I am using mask in unity and now I want to get the masked texture and save as a png file.
Unity Mask youtube video
For example, in this video, I want to get the masked image instead of the whole background image or the mask texture.
I tried (GetComponent<Mask>().graphic.mainTexture as Texture2D).GetPixels()
but it doesn't work.
Thank you very much.
Upvotes: 0
Views: 2448
Reputation: 2720
Here is implementation of what I said in comment.
Note that, mask's texture need to have same dimensions as image texture to make below code work properly. Otherwise you need to calculate which pixels overlap with mask and which not.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GetMaskedImage : MonoBehaviour
{
public Image img;
public Image mask;
public RawImage outputImg;
void Start ()
{
Texture2D output = new Texture2D(img.sprite.texture.width, img.sprite.texture.height);
for (int i = 0; i < img.sprite.texture.width; i++)
{
for (int j = 0; j < img.sprite.texture.height; j++)
{
if (mask.sprite.texture.GetPixel(i, j).a > 0.5f)
output.SetPixel(i, j, img.sprite.texture.GetPixel(i, j));
else
output.SetPixel(i, j, new Color(1f, 1f, 1f, 0f));
}
}
output.Apply();
outputImg.texture = output;
}
}
Upvotes: 1