非方形径向渐变图像生成

问题描述

我正在Unity中创建一个函数,以使用允许水平,垂直,对角线和径向方向的渐变填充纹理。前三个很容易,并且可以处理矩形图像,但是,我能找到的用于径向渐变的唯一算法取决于正方形图像,如下所示:

Vector2 center = new Vector2 ( texture.width * 0.5f,texture.height * 0.5f );
for ( int y = 0; y < texture.height; y++ )
{
    for ( int x = 0; x < texture.width; x++ )
    {
        float distanceFromCenter = Vector2.distance ( center,new Vector2 ( x,y ) );
        float t = invert ? 1 - ( 0.5f - ( distanceFromCenter / texture.width ) ) : 0.5f - ( distanceFromCenter / texture.width );
        texture.SetPixel ( x,y,gradient.Evaluate ( t ) );
    }
}

如何在矩形图像上使用它?

解决方法

问题在于texture.width的划分。使用正方形纹理时,这没关系,因为它的高度和宽度都是相同的长度。

您需要将当前点除以纹理的尺寸。这将为您提供0到1之间的x和y值。

Vector2 relativePoint = new Vector2 ( x / texture.width,y / texture.height );

接下来,获取新的中心点(0.5,0.5)与该新点之间的距离,为您提供在点(x,y)处的居中采样值。

float centeredPointSampleValue = 0.5f - Vector2.Distance ( new Vector2(0.5,0.5),relativePoint );

将它们放在一起:

for ( int y = 0; y < texture.height; y++ )
{
    for ( int x = 0; x < texture.width; x++ )
    {
        Vector2 relativePoint = new Vector2 ( x / texture.width,y / texture.height );
        float centeredPointSampleValue = 0.5f - Vector2.Distance ( new Vector2( 0.5,0.5 ),relativePoint );
        float t = invert ? 1 - centeredPointSampleValue  : centeredPointSampleValue ;
        texture.SetPixel ( x,y,gradient.Evaluate ( t ) );
    }
}