Setting pixel color out of (clamped) texture area
Posted: Sat Nov 18, 2017 2:07 pm
Hi,
I have to display a texture with its correct aspect ratio on a plane, then instead of having the border pixels stretched out over the rest of the surface have it replaced by a color.
The correct aspect ration is given that way:
I end up with something like this (left) but now want to fill the "stretched" area with a color (right)
Would you please help me understand how I should do to achieve this final result?
Thanks a lot!
My diagram at the moment
I have to display a texture with its correct aspect ratio on a plane, then instead of having the border pixels stretched out over the rest of the surface have it replaced by a color.
The correct aspect ration is given that way:
- Code: Select all
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class InitScript : MonoBehaviour
{
public GameObject screen;
public Material bmp;
void Start()
{
SetTexture(@"C:\Users\JM\Desktop\169.jpg");
}
void SetTexture(string path)
{
// Create new texture2d
Texture2D tex = LoadPNG(path);
if (tex == null)
{
return;
}
// Set width/height scale/offset for UV's
float twidth = 1.0f;
float theight = 1.0f;
float owidth = 0.0f;
float oheight = 0.0f;
if (tex.width >= tex.height)
{
theight = (float)tex.width / tex.height; // Tiling
oheight = (theight - 1) / -2; // Offset
}
else
{
twidth = (float)tex.height / tex.width;
owidth = (twidth - 1) / -2;
}
// Set texture
bmp.SetTexture("_TextureSnap", tex);
// Scale object UVs to fit texture
bmp.SetTextureScale("_TextureSnap", new Vector2(twidth, theight));
bmp.SetTextureOffset("_TextureSnap", new Vector2(owidth, oheight));
}
public static Texture2D LoadPNG(string filePath)
{
Texture2D tex = null;
byte[] fileData;
if (File.Exists(filePath))
{
fileData = File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2, TextureFormat.ARGB32, false);
tex.filterMode = FilterMode.Point;
tex.wrapMode = TextureWrapMode.Clamp;
tex.LoadImage(fileData);
}
return tex;
}
}
I end up with something like this (left) but now want to fill the "stretched" area with a color (right)
Would you please help me understand how I should do to achieve this final result?
Thanks a lot!
My diagram at the moment