2014년 5월 1일 목요일

Unity3D_Screen Capture And Mosaic


Explanation.
현재 화면을 capture한뒤 mosaic처리.
잠깐 시간이나서 구현.
최적화 X(개선필요)
모자이크 처리방식 매우 비효율적.(개선필요)
어디 쓰일지도 의문.
정리해두고 추후 필요시 사용.


CaptureAndMosaic.cs
using UnityEngine;
using System.Collections;

public class CaptureAndMosaic : MonoBehaviour
{
    int height = Screen.height;
    int width = Screen.width;

    Texture2D captureTexture;
    float startTime;

    bool draw = false;
    void Start()
    {
        startTime = Time.realtimeSinceStartup;
        StartCoroutine(getScreenAndMosaic());
    }
    void OnGUI()
    {
        if (captureTexture != null)
            GUI.DrawTexture(new Rect(0, 0, captureTexture.width, captureTexture.height), captureTexture);

        if (!string.IsNullOrEmpty(log))
            GUI.Label(new Rect(100, 100, 100, 100), log);
    }
    bool end = false;
    IEnumerator getScreenAndMosaic() 
    {
        yield return new WaitForEndOfFrame();
        captureTexture = new Texture2D(width, height, TextureFormat.RGB24, true);
        captureTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0, true);
        captureTexture.Apply();
        StartCoroutine(makeNoise());
    }

    IEnumerator makeNoise()
    {
        yield return StartCoroutine(makeNoiseTexture(40));
    }

    int index = 0;
    IEnumerator makeNoiseTexture(int dist)
    {
        int distDiv = dist;
        int nBoxSize = width / distDiv;
        int x = 0;
        int y = 1;
        Color[] colors = new Color[nBoxSize * nBoxSize];
        Color preColor = Color.white;
        int mid = height / (nBoxSize * y);
        while (nBoxSize * y < height)
        {
            preColor = captureTexture.GetPixel(0 + x * nBoxSize, height - nBoxSize * y);

            for (int i = 0; i < colors.Length; ++i)
                colors[i] = captureTexture.GetPixel(0 + x * nBoxSize, height - nBoxSize * y);
            if (height - nBoxSize * y <= 0)
                captureTexture.SetPixels(0 + x * nBoxSize, 0, nBoxSize, nBoxSize, colors);
            else
                captureTexture.SetPixels(0 + x * nBoxSize, height - nBoxSize * y, nBoxSize, nBoxSize, colors);

            ++x;

            if (x * nBoxSize > width - nBoxSize)
            {
                x = 0;
                ++y;
                if (y % 3 == 0) // 3행 처리후 apply
                {
                    captureTexture.Apply();
                    yield return null;
                }
            }
        }
        yield return null;
        captureTexture.Apply(); 

        log = "mosaic ended Time : " + (Time.realtimeSinceStartup - startTime);

        Debug.Log("end");
    }
    string log = string.Empty;

}
Result.

Before

After
Categories:

0 개의 댓글:

댓글 쓰기