LoginSignup
3
4

More than 5 years have passed since last update.

画面に四角形を敷き詰める

Last updated at Posted at 2014-11-20

C++初心者が頑張って色々覚えたのでメモ

クラス Tile を作る

x座標、y座標、幅、高さのプロパティを持ったTileクラスを作る。

Tile.h
#include "ofMain.h"

class Tile {
public:
    Tile(float x = 0, float y = 0, float w = 0, float h = 0);
    ~Tile();
    void draw();

    ofPoint pos;
    float w;
    float h;
};
Tile.cpp
#include "Tile.h"

Tile::Tile(float _x, float _y, float _w, float _h) {
    pos.x = _x;
    pos.y = _y;
    w = _w;
    h = _h;
}

void Tile::draw() {
    ofSetColor(255, 0, 0);
    ofRect(pos.x, pos.y, w, h);
}

あとはTileクラスのインスタンスを作って並べれば良いのだが、ここで2次元配列を用意する必要がある。

vector型の2次元配列

ここがハマりポイントだった。まず、変数の宣言。

ofApp.h
vector < vector<Tile *> > tiles;

vectorの中にTileクラスを格納するvector型のtiles、という意味(たぶん)

使用するときはx座標用とy座標用でforをループさせれば良いと思いきや

for (int x=0; x<100; x++) {
    for (int y=0; y<100; y++) {
        tiles[x][y] = new Tile(x*w, y*h, w, h);
    }
}

上記だとエラーになった。
調べても原因が不明だったが、Google先生が示したページではforループさせる前にresizeメソッドを実行していたので、同じようにやると

tiles.resize(100); //追加
for (int x=0; x<100; x++) {
    tiles[x].resize(100); //追加
    for (int y=0; y<100; y++) {
        tiles[x][y] = new Tile(x*w, y*h, w, h);
    }
}

うまくいきました。
動的配列なのにサイズを明示的に指定してあげなきゃいけないのはなぜなんだろう。
解決しました。コメント欄を参照ください。

四角形の大きさを求める

ひとまず動いたので良しとして、あとは分割数を設定し、画面サイズを取得して1つあたりの四角形の大きさを計算して画面に配置してやればOK。

四角形の幅 = ウインドウ幅 / 分割数
四角形の高さ = ウインドウ高さ / 分割数
ofApp.cpp
#include "ofApp.h"
void ofApp::setup(){

    ofBackground(0);

    //ウインドウサイズ
    stageWidth = ofGetWidth();
    stageHeight = ofGetHeight();

    //分割数
    sprit = 300;

    //四角形のサイズを計算
    rectWidth = stageWidth / sprit;
    rectHeight = stageHeight / sprit;

    tiles.resize(sprit);
    for (int x=0; x<sprit; x++) {
        tiles[x].resize(sprit);
        for (int y=0; y<sprit; y++) {
            tiles[x][y] = new Tile(x*rectWidth, y*rectHeight, rectWidth, rectHeight);
        }
    }
}

void ofApp::draw(){
    for (int x=0; x<sprit; x++) {
        for (int y=0; y<sprit; y++) {
            tiles[x][y]->draw();
        }
    }
}

ただし、ウインドウサイズを大きくすると大きくした分だけ隙間ができてしまうので、windowResizedメソッドで各プロパティを変更して再描画すればOK。

3
4
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4