调用 sf::矩形形状绘制函数

Calling sf::RectangleShapes draw function?

本文关键字:函数 绘制 sf 调用      更新时间:2023-10-16

我有一组简单的类。其中之一是ButtonComponent,我想基本上将sf::RectangleShape用于视觉方面,然后ButtonComponent的其余部分将处理诸如事件侦听器之类的事情。问题的形式是,如果我从父类中的sf::Drawable继承,我必须实现draw()(Component类(,这意味着子类实现父类draw()而不是SFML形状draw()函数。有没有办法重组这两个类或调用sf::RectangleShapes绘制函数的方法?

组件.h

class Component : public sf::Drawable {
public:
    Component();
    virtual ~Component();
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const = 0;
};
class ButtonComponent : public sf::RectangleShape, public Component {
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states);
};

解决方案是让子类仅继承sf::Drawable,并在子类中具有sf::RectangleShape。类似于下面的东西

class Component : public sf::Drawable {
public:
    Component();
    virtual ~Component();
    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const = 0;
};
class ButtonComponent : public Component {
public:
    ButtonComponent(const sf::Vector2f &size = sf::Vector2f(0, 0));
    void draw(sf::RenderTarget& target, sf::RenderStates states) const;
    void setSize(const sf::Vector2f& size);
    const sf::Vector2f& getSize() const;
    virtual unsigned int getPointCount() const;
    virtual sf::Vector2f getPoint(unsigned int index) const;
    void setTexture(const sf::Texture* texture, bool resetRect = false);
    void setTextureRect(const sf::IntRect &rect);
    void setFillColor(const sf::Color &color);
    void setOutlineColor(const sf::Color &color);
    void setOutlineThickness(float thickness);
    const sf::Texture* getTexture() const;
    const sf::IntRect& getTextureRext() const;
    const sf::Color& getFillColor() const;
    const sf::Color& getOutlineColor() const;
    float getOutlineThickness() const;
    sf::FloatRect getLocalBounds() const;
    sf::FloatRect getGlobalBounds() const;
    void setPosition(float x, float y);
    void setPosition(const sf::Vector2f &position);
    void setRotation(float angle);
    void setScale(float factorX, float factorY);
    void setScale(const sf::Vector2f& factors);
    void setOrigin(float x, float y);
    void setOrigin(const sf::Vector2f& origin);
    const sf::Vector2f& getPosition() const;
    float getRotation() const;
    const sf::Vector2f& getScale() const;
    const sf::Vector2f& getOrigin() const;
    void move(float offsetX, float offsetY);
    void move(const sf::Vector2f& offset);
    void rotate(float angle);
    void scale(float factorX, float factorY);
    void scale(const sf::Vector2f& factor);
    const sf::Transform& getTransform() const;
    const sf::Transform& getInverseTransform() const;
private:
    sf::RectangleShape _btnShape;
};