TextureSampler

From Unify Community Wiki
Revision as of 16:03, 10 November 2011 by Tenebrous (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Contents

Description

This is a simple class which (should) replicate the Texture2D.GetPixelBilinear function, but because it doesn't use Unity classes you can use it in other threads.

Usage

<csharp> // firstly create a new texture sampler TextureSampler tex = new TextureSampler( your Texture2D goes here );

// then get the pixel you want Color p = tex.GetPixelBilinear( 0.5f, 0.5f 0; </csharp>

Code

CSharp - TextureSampler.cs

<csharp> using UnityEngine;

public class TextureSampler {

   Color[] _data;
   int _height;
   int _width;
   public Color GetPixelBilinear( float u, float v )
   {
       // from: http://en.wikipedia.org/wiki/Bilinear_filtering#Sample_code
       u *= _width;
       v *= _height;
       int x = Mathf.FloorToInt( u );
       int y = Mathf.FloorToInt( v );
       float u_ratio = u - x;
       float v_ratio = v - y;
       float u_opposite = 1 - u_ratio;
       float v_opposite = 1 - v_ratio;
       return ( ( GetPixel( x, y ) * u_opposite + GetPixel( x + 1, y ) * u_ratio ) * v_opposite
             + ( GetPixel( x, y + 1 ) * u_opposite + GetPixel( x + 1, y + 1 ) * u_ratio ) * v_ratio
             );
   }
   public Color GetPixel( float x, float y )
   {
       int xi = (int)WrapBetween( x, 0.0f, (float)_width );
       int yi = (int)WrapBetween( y, 0.0f, (float)_height );
       return ( _data[yi * _width + xi] );
   }
   float Mod( float x, float y )
   {
       // from http://stackoverflow.com/questions/4633177/c-how-to-wrap-a-float-to-the-interval-pi-pi
       if( 0 == y )
           return( x );
       return( x - y * Mathf.Floor(x/y) );
   }
   float WrapBetween( float value, float min, float max )
   {
       return Mod( value - min, max - min ) + min;
   }
   public TextureSampler( Texture2D source )
   {
       _data = source.GetPixels();
       _width = source.width;
       _height = source.height;
   }

} </csharp>

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox