微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

非方形径向渐变图像生成

如何解决非方形径向渐变图像生成

我正在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 ) );
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。