Esempio n. 1
0
void sf::ApplyGradient(sf::Shape& shape, Orientation::Type orientation, const sf::Color& color1, const sf::Color& color2, bool applyOnBorder)
{
    if(orientation != sf::Orientation::NONE)
    {
        sf::FloatRect shapeRect(shape.GetPointPosition(0), sf::Vector2f(0.f,0.f));
        sf::Vector2f rectRightBottomCorner(0.f,0.f);

        // Define left and top limits
        for(unsigned int i = 0; i < shape.GetPointsCount(); ++i)
        {
            sf::Vector2f pointPosition = shape.GetPointPosition(i);
            shapeRect.Left = (pointPosition.x < shapeRect.Left) ? pointPosition.x : shapeRect.Left;
            shapeRect.Top = (pointPosition.y < shapeRect.Top) ? pointPosition.y : shapeRect.Top;
            rectRightBottomCorner.x = (pointPosition.x > rectRightBottomCorner.x) ? pointPosition.x : rectRightBottomCorner.x;
            rectRightBottomCorner.y = (pointPosition.y > rectRightBottomCorner.y) ? pointPosition.y : rectRightBottomCorner.y;
        }
        shapeRect.Width = rectRightBottomCorner.x-shapeRect.Left;
        shapeRect.Height = rectRightBottomCorner.y-shapeRect.Top;

        // Apply gradient
        for(unsigned int i = 0; i < shape.GetPointsCount(); ++i)
        {
            float factor = 0.f;
            sf::Vector2f pointPosition = shape.GetPointPosition(i);
            switch(orientation)
            {
            case Orientation::TOPTOBOTTOM :
                factor = 1-(pointPosition.y-shapeRect.Top)/shapeRect.Height;
                break;

            case Orientation::BOTTOMTOTOP :
                factor = (pointPosition.y-shapeRect.Top)/shapeRect.Height;
                break;

            case Orientation::LEFTTORIGHT :
                factor = 1-(pointPosition.x-shapeRect.Left)/shapeRect.Width;
                break;

            case Orientation::RIGHTTOLEFT :
                factor = (pointPosition.x-shapeRect.Left)/shapeRect.Width;
                break;

            default :
                factor = 1;
                break;
            }
            if(applyOnBorder)
                shape.SetPointOutlineColor(i, sf::Color(factor*color1.r+(1-factor)*color2.r, factor*color1.g+(1-factor)*color2.g, factor*color1.b+(1-factor)*color2.b, factor*color1.a+(1-factor)*color2.a));
            else
                shape.SetPointColor(i, sf::Color(factor*color1.r+(1-factor)*color2.r, factor*color1.g+(1-factor)*color2.g, factor*color1.b+(1-factor)*color2.b, factor*color1.a+(1-factor)*color2.a));
        }
    }
}