TextureSampler

From Unify Community Wiki
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

// 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;

Code

Please feel free to do what you like with this code. The only thing I ask is that you let me know if you use it for anything interesting :)


CSharp - TextureSampler.cs

// I'd love to hear from you if you do anything cool with this or have any suggestions :)
// www.tenebrous.co.uk
 
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;
    }
}
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox