Share via


방법: 스프라이트 사용

업데이트: 2007년 11월

화면에 이미지 및 텍스트를 그려 넣기 위해 스프라이트를 사용할 수 있습니다. 이 예제에서는 그리기 및 렌더링 작업을 보여 줍니다.

이 코드 예제의 폼에는 다음 개체가 포함되어 있습니다.

이 코드 예제는 파일에서 질감을 로드하여 스프라이트를 만듭니다. 장치나 에뮬레이터로 배포할 작은 비트맵을 프로젝트에 포함시켜야 합니다.

폼 생성자는 장치의 PresentationParameters 속성 설정을 지정하고, Device 개체를 만들고, 장치의 Reset 메서드를 호출합니다. 또한 Font 개체도 생성합니다.

다음 표에서는 스프라이트를 렌더링하는 샘플 메서드를 설명합니다.

참고:

관리되는 Direct3D 모바일 응용 프로그램을 사용하려면 Pocket PC 및 Smartphone용 Windows Mobile 버전 5.0 소프트웨어가 필요합니다. Windows Mobile 소프트웨어 및 SDK에 대한 내용은 .NET Compact Framework용 외부 리소스를 참조하십시오.

메서드

작업

OnDeviceReset

  • 비트맵 파일에서 질감을 로드합니다.

OnPaint

  1. 장면을 시작합니다.

  2. SpriteFlags 플래그를 지정합니다. 자세한 내용은 이 항목의 뒷부분에 나오는 "강력한 프로그래밍" 단원을 참조하십시오.

  3. 화면에 스프라이트와 텍스트를 그립니다.

  4. 장면을 끝냅니다.

예제

다음 코드 예제에서는 완전한 폼을 제공합니다. 이 예제에서는 제공된 비트맵을 사용하여 스프라이트를 그립니다.

Class Sprites
    Inherits Form
    ' The objects that will be used to show
    ' the uses of the Sprite class
    Private device As Device
    Private d3dFont As Microsoft.WindowsMobile.DirectX.Direct3D.Font
    Private sprite As Sprite
    Private texture As Texture


    Public Sub New() 
        Dim present As PresentParameters
        Dim gdiFont As System.Drawing.Font

        Me.Text = "Using Sprites"

        ' Give the application a way to be closed.
        ' This must be done before the device is created
        ' as it will cause the hwnd of the Form to change.
        Me.MinimizeBox = False

        present = New PresentParameters()
        present.Windowed = True
        present.SwapEffect = SwapEffect.Discard

        device = New Device(0, DeviceType.Default, Me, CreateFlags.None, present)
        AddHandler device.DeviceReset, AddressOf OnDeviceReset

        ' Construct a new Sprite.
        ' Sprites do not need to be recreated
        ' when a device is reset.
        sprite = New Sprite(device)

        gdiFont = New System.Drawing.Font(FontFamily.GenericSansSerif, 10F, FontStyle.Regular)

        ' Construct a new font. Fonts do not need
        ' to be recreated when a device is reset.
        d3dFont = New Microsoft.WindowsMobile.DirectX.Direct3D.Font(device, gdiFont)

        OnDeviceReset(Nothing, EventArgs.Empty)

    End Sub


    Private Sub OnDeviceReset(ByVal sender As Object, ByVal e As EventArgs) 
        ' Textures must be recreated whenever a device is reset
        ' no matter what pool they are created in.
        texture = TextureLoader.FromFile(device, "image.bmp")

    End Sub


    Protected Overrides Sub OnPaintBackground(ByVal e As PaintEventArgs) 
        ' Do nothing.
    End Sub

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        ' Begin the scene and clear the back buffer to black
        device.BeginScene()
        device.Clear(ClearFlags.Target, Color.Black, 1.0F, 0)

        ' When using sprites it is important to
        ' specify sprite flags passed to Sprite.Begin
        sprite.Begin(SpriteFlags.SortTexture Or SpriteFlags.AlphaBlend)

        ' Draw an image to the screen using Sprite.Draw
        Dim spriteY As Integer = 5

        sprite.Draw(texture, Vector3.Empty, New Vector3(0, spriteY, 0), Color.White.ToArgb())
        spriteY += texture.GetLevelDescription(0).Height + 5

        ' Draw a portion of an image to the screen
        ' using Sprite.Draw. This shall be drawn such
        ' that the image is modulated with the color green.
        sprite.Draw(texture, New Rectangle(4, 4, 24, 24), Vector3.Empty, New Vector3(0, spriteY, 0), Color.Green)

        spriteY += 30

        ' Draw text to the screen. Using a sprite to draw text
        ' to the  screen is essential for good performance.
        ' Otherwise the font object will perform a
        ' Sprite.Begin/Sprite.End internally for
        ' each call to Font.DrawText. This can cause severe
        ' performance problems.
        spriteY = 150

        d3dFont.DrawText(sprite, "This is text.", 5, spriteY, Color.Red)
        spriteY += d3dFont.Description.Height + 5

        d3dFont.DrawText(sprite, "This is another line of text.", 5, spriteY, Color.Green)
        spriteY += d3dFont.Description.Height + 5

        d3dFont.DrawText(sprite, "Only one call to Sprite.Begin.", 5, spriteY, Color.Blue)

        ' End drawing using this sprite. This will cause the
        ' sprites to be flushed to the graphics driver and will
        ' reset the transformation matrices, textures states,
        ' and renderstates if the SpriteFlags specified in Begin
        ' call for that to happen.
        sprite.End()

        ' Finish the scene and present it on the screen.
        device.EndScene()
        device.Present()

    End Sub


    Shared Sub Main() 
        Application.Run(New Sprites())

    End Sub
End Class
class Sprites : Form
{
    // The objects that will be used to show
    // the uses of the Sprite class
    private Device device;
    private Microsoft.WindowsMobile.DirectX.Direct3D.Font d3dFont;
    private Sprite sprite;
    private Texture texture;

    public Sprites()
    {
        PresentParameters present;
        System.Drawing.Font gdiFont;

        this.Text = "Using Sprites";

        // Give the application a way to be closed.
        // This must be done before the device is created
        // as it will cause the hwnd of the Form to change.
        this.MinimizeBox = false;

        present = new PresentParameters();
        present.Windowed = true;
        present.SwapEffect = SwapEffect.Discard;

        device = new Device(0, DeviceType.Default, this,
            CreateFlags.None, present);
        device.DeviceReset += new EventHandler(OnDeviceReset);

        // Construct a new Sprite.
        // Sprites do not need to be recreated
        // when a device is reset.
        sprite = new Sprite(device);

        gdiFont = new System.Drawing.Font
            (FontFamily.GenericSansSerif,
        10.0f, FontStyle.Regular);

        // Construct a new font. Fonts do not need
        // to be recreated when a device is reset.
        d3dFont= new Microsoft.WindowsMobile.DirectX.Direct3D.Font
            (device, gdiFont);

        OnDeviceReset(null, EventArgs.Empty);
    }

    private void OnDeviceReset(object sender, EventArgs e)
    {
        // Textures must be recreated whenever a device is reset
        // no matter what pool they are created in.
        texture = TextureLoader.FromFile(device, "image.bmp");
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        // Do nothing.
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        // Begin the scene and clear the back buffer to black
        device.BeginScene();
        device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0);

        // When using sprites it is important to
        // specify sprite flags passed to Sprite.Begin

        sprite.Begin(SpriteFlags.SortTexture | SpriteFlags.AlphaBlend);

        // Draw an image to the screen using Sprite.Draw

        int spriteY = 5;

        sprite.Draw(texture, Vector3.Empty, new Vector3(0,
            spriteY, 0),
            Color.White.ToArgb());
        spriteY += texture.GetLevelDescription(0).Height + 5;

        // Draw a portion of an image to the screen
        // using Sprite.Draw. This shall be drawn such
        // that the image is modulated with the color green.

        sprite.Draw(texture, new Rectangle(4, 4, 24, 24),
            Vector3.Empty,
            new Vector3(0, spriteY, 0), Color.Green);

        spriteY+= 30;

        // Draw text to the screen. Using a sprite to draw text
        // to the  screen is essential for good performance.
        // Otherwise the font object will perform a
        // Sprite.Begin/Sprite.End internally for
        // each call to Font.DrawText. This can cause severe
        // performance problems.

        spriteY = 150;

        d3dFont.DrawText(sprite, "This is text.",
            5, spriteY, Color.Red);
        spriteY += d3dFont.Description.Height + 5;

        d3dFont.DrawText(sprite, "This is another line of text.",
            5, spriteY, Color.Green);
        spriteY += d3dFont.Description.Height + 5;

        d3dFont.DrawText(sprite, "Only one call to Sprite.Begin.",
            5, spriteY, Color.Blue);

        // End drawing using this sprite. This will cause the
        // sprites to be flushed to the graphics driver and will
        // reset the transformation matrices, textures states,
        // and renderstates if the SpriteFlags specified in Begin
        // call for that to happen.
        sprite.End();

        // Finish the scene and present it on the screen.
        device.EndScene();
        device.Present();
    }

    static void Main()
    {
        Application.Run(new Sprites());
    }
}

코드 컴파일

이 예제에는 다음과 같은 네임스페이스에 대한 참조가 필요합니다.

강력한 프로그래밍

장치를 다시 설정할 때 다시 만들 필요가 없도록 폼의 생성자에 스프라이트 및 글꼴을 만듭니다.

성능을 향상시키려면 스프라이트를 사용하여 텍스트를 그립니다. 그렇지 않으면 글꼴 개체는 DrawText를 호출할 때마다 스프라이트 BeginEnd 메서드를 내부적으로 수행합니다.

가능하면 한 프레임에 대해 하나의 스프라이트를 사용할 때 스프라이트에 대한 BeginEnd 메서드를 호출하는 하나의 호출에 스프라이트를 중첩합니다.

다음 SpriteFlags 값을 지정하여 렌더링을 최적화하고 성능을 향상시킬 수 있습니다.

  • SortTexture는 질감 간을 더 빠르게 전환할 수 있도록 이미지를 미리 정렬한 후 화면에 그립니다.

  • AlphaBlend는 글꼴을 바르게 렌더링하며 투명하거나 반투명한 영역이 있는 스프라이트에서 올바른 글꼴을 나타내는 데 특히 도움이 됩니다.

  • SortDepthBackToFront는 앞에서 뒤로 스프라이트를 정렬하므로 반투명하거나 투명한 스프라이트를 서로의 위에 그려야 할 경우에 유용합니다.

  • DoNotSaveState는 지정된 렌더링 상태를 사용할 수 없는 응용 프로그램의 성능을 향상시킵니다.

  • DoNotModifyRenderState는 현재의 렌더링 상태를 사용하여 성능을 최적화하며 특수 효과를 나타내기 위해 사용할 수 있습니다.

  • ObjectSpaceBillboard를 사용하여 다른 특수 효과를 나타내는 이미지를 그릴 수 있습니다.

참고 항목

개념

.NET Compact Framework 방법 항목

기타 리소스

.NET Compact Framework의 모바일 Direct3D 프로그래밍