カテゴリー
C++ JUCE

JUCEでRectangleをdrawする

JUCEで四角いシェイプを描画する方法として、カスタムComponentクラスを用意し、paintメソッドに記述します。

AudioProcessorEditorクラスにCustomComponentをレイアウトする場合、以下のpattern 1 〜 3は同じ結果をもたらします。

// CustomComponent.h

class CustomComponent: public juce::Component {
public:

  void paint(juce::Graphics& g) override
  {
    // pattern 1
    g.fillAll(juce::Colurs::orange);
    
    // pattern 2
    auto rect = getLocalBounds();
    g.setColour(juce::Colours::orange);
    g.fillRect(rect);

    // pattern 3
    g.setColour(juce::Colours::orange);
    juce::Path path;
    path.startNewSubPath(rect.getX(), rect.getY());
    path.lineTo(rect.getX(), rect.getHeight());
    path.lineTo(rect.getWidth(), rect.getHeight());
    path.lineTo(rect.getWidth(), rect.getY());
    path.closeSubPath();
    g.fillPath(path); 

    // pattern 4
    g.setColour(juce::Colours::orange);
    juce::Path path;
    // directly adding rect to the path
    auto rect = getLocalBounds();
    path.addRectangle(rect);
    g.fillPath(path);

    // pattern 5
    g.setColour(juce::Colours::orange);
    juce::Path path;
    auto rect = getLocalBounds();
    // draw rounded corner
    float cornerRadius = 10.f;
    path.addRoundedRectangle(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight(), cornerRadius);
    g.fillPath(path);

    // pattern 6
    // draw rounded rect using Rectangle<float>
    const float borderWidth = 2.f;
    const float cornerRadius = 10.f;
    const juce::Rectangle<float> rect = getLocalBounds().toFloat().reduced(borderWidth / 2.f);
    
    g.setColour(juce::Colours::grey);
    g.drawRoundedRectangle(rect, cornerRadius, borderWidth);

    // pattern 7
    auto rect = getLocalBounds();
    g.setColour(juce::Colours::black);
    juce::Path path;
    path.addRoundedRectangle(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight(), rect.getWidth/2);
    g.fillPath(path);
  }

  
}
// AudioProcessorEditor.cpp

void AudioProcessorEditor::resized()
{
  auto area = getLocalBounds();
  auto width = area.getWidth();
  auto height = area.getHeight();
  float componentWidth = 100.f;
  float componentHeight = 100.f;
  customComponent.setBounds(width/2 - componentWidth/2, height/2 - componentHeight/2, componentWidth, componentHeight);
}