首页 > 解决方案 > 如何为渐变绘制斜角

问题描述

我不完全确定如何命名,但是,我正在尝试在 Unity 中编写一个函数来创建渐变边框图像,并且我可以获取渐变的第一个边缘来绘制角度但是,我不知道了解如何使其正常工作。

当前结果:

在此处输入图像描述

预期结果:

在此处输入图像描述

我目前的代码:

public static Texture2D CreateBorder ( this Gradient gradient, int width, int height, int borderSize ) {
    Texture2D texture = new Texture2D ( width, height );

    // Create Base
    for(int y=0;y<height;y++) {
        for(int x=0;x<width;x++) {
            texture.SetPixel ( x, y, gradient.Evaluate ( 1f ) );
        }
    }

    // Create Bottom
    for ( int y = 0; y < borderSize; y++ ) {
        for ( int x = borderSize; x < ( width - borderSize ); x++ ) {
            float t = (float) y / borderSize;
            texture.SetPixel ( x, y, gradient.Evaluate ( t ) );
        }
    }

    // Create Left
    for ( int y = borderSize; y < ( height - borderSize ); y++ ) {
        for ( int x = 0; x < borderSize; x++ ) {
            float t = (float) x / borderSize;
            texture.SetPixel ( x, y, gradient.Evaluate ( t ) );
        }
    }

    // Create Top
    for ( int y = height-borderSize; y < height; y++ ) {
        for ( int x = borderSize; x < (width-borderSize); x++ ) {
            float t = (float) (height-y) / borderSize;
            texture.SetPixel ( x, y, gradient.Evaluate ( t ) );
        }
    }

    // Create Right
    for ( int y = borderSize; y < (height-borderSize); y++ ) {
        for ( int x = (width-borderSize); x < width; x++ ) {
            float t = (float) ( width - x ) / borderSize;
            texture.SetPixel ( x, y, gradient.Evaluate ( t ) );
        }
    }

    texture.Apply ();
    return texture;
}

我似乎无法弄清楚如何在不相互覆盖的情况下使角落相遇。

标签: c#unity3d

解决方案


这个答案可能不是最有效的,但它的工作原理......

public static Texture2D CreateBorder ( this Gradient gradient, int width, int height, int borderSize ) {
    Texture2D texture = new Texture2D ( width, height );

    // Create Gradient
    for ( int i = 0; i < borderSize; i++ ) {
        for ( int y = i; y < height - i; y++ ) {
            for ( int x = i; x < width - i; x++ ) {
                float t = (float) i / borderSize;
                texture.SetPixel ( x, y, gradient.Evaluate ( t ) );
            }
        }
    }

    // Create Background
    for ( int y = borderSize; y < height - borderSize; y++ ) {
        for ( int x = borderSize; x < width - borderSize; x++ ) {
            texture.SetPixel ( x, y, Color.clear );
        }
    }

    texture.Apply ();
    return texture;
}

推荐阅读