How can I create a random number of D2D shapes (rectangles and ellipses) and refer to them as an array while drawing?

StackOverflow https://stackoverflow.com/questions/4474943

سؤال

Let me elaborate. I define a D2D Rectangle like so:

D2D1_RECT_F rect1 = D2D1::RectF(5, 0, 150, 150);

and an ellipse as:

D2D1_ELLIPSE ellipse1 = D2D1::Ellipse(D2D1::Point2F(75.f, 75.f), 75.f, 75.f);

To draw these shapes, I first transform them and pass them to the rendertarget:

m_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Translation(D2D1::SizeF(200, 50)));
m_pRenderTarget->FillRectangle(&rect1, m_pLinearGradientBrush);

I'd like a way to create a random number of rectangles and ellipses, and store them in an array, and then be able to draw them as well. I have a function that returns a random number from zero to five. I want to be able to use that number to create an array that points to these shapes, and iterates through them to draw them to the screen. Any ideas on how I can approach this problem?

هل كانت مفيدة؟

المحلول

You could achieve this is one of 2 ways:

Option 1 - Create 2 arrays containing Rectangles and Ellipses respectively. Then we you want to choose a random shape to draw, you first pick the random array (choosing whether to draw an ellipse or rect), and then choose a particular rect/ellipse from that array.

Option 2 - Use OO to create a polymorphic Draw functions.

// Define new base class for your shapes
class DrawableShape
{
    HRESULT DrawMe(ID2D1RenderTarget* pUseThisRT);
};

// Create a MyD2DEllipse class implementing DrawableShape
class MyD2DEllipse : public D2D1_RECT_F, public DrawableShape
{
    HRESULT DrawMe(... pUseThisRT)
    {
        pUseThisRT->FillEllipse(this, ...);
    }
};

// Similarly create MyD2DRectangle
class MyD2DRectangle : ..
{
    ...
};

You can then create an array of DrawableShape[] from which you can choose randomly from.

void DrawRandomShape(DrawableShape* shapes[])
{
   shapes[rand()]->DrawMe(pUseThisRT);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top