Presentation is loading. Please wait.

Presentation is loading. Please wait.

XNA 4.0 Sprites & Fonts 靜宜大學資工系 蔡奇偉 副教授 © 2011.

Similar presentations


Presentation on theme: "XNA 4.0 Sprites & Fonts 靜宜大學資工系 蔡奇偉 副教授 © 2011."— Presentation transcript:

1 XNA 4.0 Sprites & Fonts 靜宜大學資工系 蔡奇偉 副教授 © 2011

2 大綱 What is a Sprite Screen Coordinate System Sprite Origin
Sprite Depth Color Key Alpha Blending Drawing a Sprite SpriteBatch Class 範例 Rendering Text 參考資料

3 What is a Sprite Sprites are 2D bitmaps that are drawn directly to a render target without using the pipeline for transformations, lighting or effects. Sprites are commonly used to display information such as health bars, number of lives, or text such as scores. Some games, especially older games, are composed entirely of sprites.

4 Screen Coordinate System
800×480 X Y (0, 0) 479 799

5 Sprite Origin Sprite 的左上角為預設的原點位置 繪製 Sprite 時,Sprite 原點將貼齊指定的位置 (0, 0)
x y 繪製 Sprite 時,Sprite 原點將貼齊指定的位置 預設原點 中央原點 (400,200)

6 Sprite Depth 我們可以用是一個介於 0.0與 1.0之間的數值來指定 sprite 的深度(depth)。0.0 代表近方,1.0 代表遠方。我們可以在畫一組 sprites 時,要求按照由遠而近(深度值遞減)的順序或由近而遠(深度值遞增)的順序來繪製。 1 Front Back

7 Color Key 我們可以啟動透明色(color key)的功能,並指定圖片中的某一顏色作為透明色。繪製圖片時,透明色的區域會顯示背景的圖案。當建置專案時,圖片格式轉換的過程中,會把該圖片中的所有透明色像素全部改以 Color.Transparent (R:0, G:0, B:0, A:0)。所以程式讀入的圖檔,其透明色的值都是 Color.Transparent。 沒有透明色 黑色當透明色

8 更改 Color Key XNA 預設為啟動透明色的功能,並以洋紅色( R:255, G:0, B:255)為透明色。在 Visual Studio 的方案總管中,在圖片檔按下滑鼠右鍵後,選「屬性」以開啟其「檔案屬性」面板。如右圖所示,在 Content Processor的欄位中,我們可以改變透明色的顏色,或關閉透明的功能。 註:使用 color key 的圖片應避免使用如 jpg 格式般的失真性壓縮。

9 Alpha Blending Destination(目標) 紅色區域 alpha = 1.0 Source(來源)

10 假定左圖中,紅色區域的 alpha 值固定為 1.0(即完全不透明),白色區域的 alpha 值變動如其他三圖所示。

11 Drawing a Sprite Derive a class from Game.
Define a SpriteBatch object as a field on your game class. 1 2

12 In your LoadContent method, construct the SpriteBatch object, passing the current graphics device.
Load the textures that will be used for drawing sprites in LoadContent. private Texture2D SpriteTexture; protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); SpriteTexture = Content.Load<Texture2D>("ship"); } 3 4

13 In the overridden Draw method, call Clear.
After Clear, call Begin on your SpriteBatch object. Create a Vector2 to represent the screen position of the sprite. Call Draw on your SpriteBatch object, passing the texture to draw, the screen position, and the color to apply. Use Color.White to draw the texture without any color effects. When all the sprites have been drawn, call End on your SpriteBatch object.

14 protected override void Draw(GameTime gameTime) {
GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); Vector2 pos = new Vector2(100, 200); spriteBatch.Draw(SpriteTexture, pos, Color.White); spriteBatch.End(); base.Draw(gameTime); } 5 6 7 8 9

15 SpriteBatch Class 用於繪製一批具有相同設定的 sprites。 Constructor
public SpriteBatch (GraphicsDevice graphicsDevice) 範例 SpriteBatch spriteBatch; spriteBatch = new SpriteBatch(GraphicsDevice);

16 Public Methods Begins a sprite batch operation. public void Begin () public void Begin (SpriteSortMode sortMode, BlendState blendState) sortMode 若為 null,代表預設值 SpriteSortMode.Defered。 blendState 若為 null,代表預設值 BlendState.AlphaBlend。

17 SpriteSortMode public enum SpriteSortMode; 成員名稱 說明 Defered Immediate
Sprites are not drawn until End is called. End will apply graphics device settings and draw all the sprites in one batch, in the same order calls to Draw were received. This mode allows Draw calls to two or more instances of SpriteBatch without introducing conflicting graphics device settings. SpriteBatch defaults to Deferred mode. Immediate Begin will apply new graphics device settings, and sprites will be drawn within each Draw call. In Immediate mode there can only be one active SpriteBatch instance without introducing conflicting device settings.

18 BackToFront FrontToBack Texture
Same as Deferred mode, except sprites are sorted by depth in back-to-front order prior to drawing. This procedure is recommended when drawing transparent sprites of varying depths. FrontToBack Same as Deferred mode, except sprites are sorted by depth in front-to-back order prior to drawing. This procedure is recommended when drawing opaque sprites of varying depths. Texture Same as Deferred mode, except sprites are sorted by texture prior to drawing. This can improve performance when drawing non-overlapping sprites of uniform depth.

19 Adds a sprite to a batch of sprites to be rendered.
Public Methods Adds a sprite to a batch of sprites to be rendered. public void Draw (Texture2D texture, Vector2 position, Color color) texture A texture. position The location (in screen coordinates) to draw the sprite. color The color to tint a sprite. Use Color.White for full color with no tinting. position texture

20 Public Methods public void Draw (Texture2D texture, Vector2 position, Nullable<Rectangle> sourceRectangle, Color color) sourceRectangle A rectangle that specifies (in texels) the source texels from a texture. Use null to draw the entire texture. position sourceRectangle texture

21 Public Methods public void Draw (Texture2D texture, Rectangle destinationRectangle, Color color) destinationRectangle A rectangle that specifies (in screen coordinates) the destination for drawing the sprite. If this rectangle is not the same size as the source rectangle, the sprite will be scaled to fit. destinationRectangle texture

22 Public Methods public void Draw (Texture2D texture, Rectangle destinationRectangle, Nullable<Rectangle> sourceRectangle, Color color) destinationRectangle sourceRectangle

23 Public Methods public void Draw (Texture2D texture, Vector2 position, Nullable<Rectangle> sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth) rotation Specifies the angle (in radians) to rotate the sprite about its center. origin The sprite origin; the default is (0,0) which represents the upper-left corner. scale Scale factor. effects Effects to apply. layerDepth The depth of a layer. By default, 0 represents the front layer and 1 represents a back layer. Use SpriteSortMode if you want sprites to be sorted during drawing.

24 SpriteEffects public enum SpriteEffects; 成員名稱 說明 FlipHorizontally
Rotate 180 degrees about the Y axis before rendering. FlipVertically Rotate 180 degrees about the X axis before rendering. None No rotations specified. FlipHorizontally FlipVertically

25 Public Methods public void Draw (Texture2D texture, Vector2 position, Nullable<Rectangle> sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth) scale Scale factor (sx, sy).

26 Public Methods public void Draw (Texture2D texture, Rectangle destinationRectangle, Nullable<Rectangle> sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth) destinationRectangle 提供繪圖位置與縮放比例的資訊

27 Draw 功能總結 指定繪圖位置 縮放繪圖 可選取來源圖片的部分來繪製 改變繪圖色調 旋轉繪圖 改變繪圖原點 套用垂直翻轉或水平翻轉的特效
指定繪圖深度

28 Public Methods Flushes the sprite batch and restores the device state to how it was before Begin was called. public void End ()

29 範例一:把一個 sprite 繪製在 Viewport 的正中央
(CenterOfViewport.rar) 觀察一:Viewport 存在 Game 的資料成員 GraphicsDevice 中,即 GraphicsDevice.Viewport。 觀察二:Viewport 預設等同於遊戲視窗。 觀察三:Viewport 的位置與大小可由其屬性 X, Y, Width, 和 Height 讀出。 觀察四:圖片的大小可由其屬性 Width, 和 Height 讀出。

30 x = X + W/2 – w/2 = X + (W – w)/2 y = Y + H/2 – h/2 = Y + (H – h)/2
觀察五:圖片的繪製位置可由下圖推導出來。 Viewport (X,Y) (x,y) h H w W x = X + W/2 – w/2 = X + (W – w)/2 y = Y + H/2 – h/2 = Y + (H – h)/2

31 Vector2 CenterOfViewport (Viewport v)
{ Vector2 center = new Vector2(v.X + v.Width/2, v.Y+v.Height/2); return center; } protected override void Draw(GameTime gameTime) GraphicsDevice.Clear(backgroundColor); Vector2 cov = CenterOfViewport (GraphicsDevice.Viewport); Vector2 position = new Vector2( cov.X – sprite.Width/2, cov.Y – sprite.Height/2); spriteBatch.Begin(); spriteBatch.Draw(sprite, position, Color.White); spriteBatch.End(); base.Draw(gameTime);

32 執行結果

33 範例二:把一個 sprite 旋轉繪製在 Viewport 的正中央
(RotateSprite.rar) 觀察一:sprite 原點必須由左上角移至圖片中心,並與繪圖位置重合。 觀察二:如下圖所示,順時針旋轉,角度為弳度單位。 Viewport

34 protected override void Draw(GameTime gameTime)
{ GraphicsDevice.Clear(backgroundColor); Vector2 cov = CenterOfViewport(GraphicsDevice.Viewport); Vector2 sprite_origin = new Vector2(sprite.Width/2, sprite.Height/2); spriteBatch.Begin(); spriteBatch.Draw(sprite, cov, null, Color.White, (float) (Math.PI / 6.0), sprite_origin, , SpriteEffects.None, 0); spriteBatch.End(); base.Draw(gameTime); }

35 執行結果

36 範例三:SpriteSortMode 觀察一:在 spriteBatch.Begin 中指定排序方式。
(SpriteSortOrder.rar) 觀察一:在 spriteBatch.Begin 中指定排序方式。 觀察二:在 spriteBatch.Draw 中指定個別 sprite 的深度 。

37 void DrawSprite (Texture2D sprite, Vector2 position, float order)
{ spriteBatch.Draw (sprite, position, null, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, order); } void DrawSprites (SpriteSortMode mode, int xoffset) spriteBatch.Begin(mode, BlendState.AlphaBlend); DrawSprite(sprite1, new Vector2(xoffset, 100), f); // 中 DrawSprite(sprite2, new Vector2(xoffset+75, 175), 0 ); // 前 DrawSprite(sprite3, new Vector2(xoffset+150, 250), 1 ); // 後

38 執行結果 DrawSprites(SpriteSortMode.Deferred, 85);
DrawSprites(SpriteSortMode.BackToFront, 285); DrawSprites(SpriteSortMode.FrontToBack, 485);

39 Rendering Text 在 XNA 中加入文字顯示需經以下三個步驟:
在專案中加入 Sprite Font 資源。 在程式碼中載入前述之 Sprite Font 資源。 利用 SpriteBatch 的 DrawString 方法來繪出字 串。 利用 SpriteFont.MeasureString 來計算字串的 寬與高。 顯示中文字

40 在專案中加入 Sprite Font 資源 Step 1: 在左方 Content 專案項目按下滑鼠右鍵,選 [加入 → 新增項目]。

41 1 選取這一項 2 命名(副檔名需保持 .spritefont) 3

42 新增這一項

43 .spritefont 檔案格式解說 XML 格式的文字檔。
<FontName>Segoe UI Mono</FontName> 字型名稱 <Size>14</Size> 文字大小(單位為 point) <Style>Regular</Style> 文字樣式:Regular, Bold, Italic(標準、粗體、斜體)

44 <CharacterRegions> <CharacterRegion>
<!-- CharacterRegions control what letters are available in the font. Every character from Start to End will be built and made available for drawing. The default range is from 32, (ASCII space), to 126, ('~'), covering the basic Latin character set. The characters are ordered according to the Unicode standard. See the documentation for more information. --> <CharacterRegions> <CharacterRegion> <Start> </Start> <End>~</End> </CharacterRegion> </CharacterRegions>

45 字型名稱

46 在程式碼中載入前述之 Sprite Font 資源
Step 1: 在 Game1 中宣告一個型態為 SpriteFont 的物件,如下所示:

47 在程式碼中載入前述之 Sprite Font 資源
Step 2: 在 LoadContent 中載入字型,如下所示:

48 利用 SpriteBatch 的 DrawString 方法來繪出字串。

49 FontDemo 程式執行的畫面(14 point 大小的文字)

50 FontDemo 程式執行的畫面(24 point 大小的文字)

51 利用 SpriteFont.MeasureString 來計算字串的寬與高
public Vector2 MeasureString (string text) 參數 text 是欲測量寬與高的字串。 傳回值為 Vector2 型態,其中 X 為寬度,Y 為高度,單位都是像素。 範例 Vector2 size = font.MeasureString(“Hello, XNA”); // size.X 是寬度 // size.Y 是高度

52 FontDemo2 程式執行的畫面(24 point 大小的文字)

53 顯示中文字 把程式用到的所有中文字,按照左圖所示的格式加進字型描述檔中。 string msg = "哈囉, XNA";
float msgWidth = font.MeasureString(msg).X; Vector2 position = new Vector2((graphics.PreferredBackBufferWidth - msgWidth) / 2, 0); spriteBatch.Begin(); spriteBatch.DrawString(font, msg, position, Color.White); spriteBatch.End();

54 FontDemo3 程式執行的畫面(24 point 大小的文字)

55 SpriteFont Class

56 SpriteBatch.DrawString() 方法


Download ppt "XNA 4.0 Sprites & Fonts 靜宜大學資工系 蔡奇偉 副教授 © 2011."

Similar presentations


Ads by Google