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

Slides:



Advertisements
Similar presentations
Chapter 2 Combinatorial Analysis 主講人 : 虞台文. Content Basic Procedure for Probability Calculation Counting – Ordered Samples with Replacement – Ordered.
Advertisements

第一單元 建立java 程式.
Java Programming Hygiene - for DIDC
CATIA V5 Training CATIA V5 装配设计 Assembly Design.
你的 够多吗? 手段 西北中文学校 Northwest Chinese School 陈婷 Ting Chen.
项目:贪吃蛇游戏设计 工作任务一:系统设计(system design) 工作任务二:豆类(Bean)设计
“走进三国” 读书汇报会 广州市玉岩中学 李玉明( ).
第一章 面向对象程序设计.
類別與物件 Class & Object.
税务认定 永州市国家税务局纳税人学校.
手持式裝置之隨身照護應用 Android開發環境設定 鐘國家 老師.
指導教授:許子衡 教授 報告學生:翁偉傑 Qiangyuan Yu , Geert Heijenk
你的學員對你的教學表現隨時在給回饋 - 他們透過肢體語言給我們打分數
Chapter 2. The Graphics Rendering Pipeline 图形绘制流水线
Classes Lecturer: 曾學文.
Creating Animated Apps (I) 靜宜大學資管系 楊子青
Chapter 6 Advanced UI Design.
Draft Amendment to STANDARD FOR Information Technology -Telecommunications and Information Exchange Between Systems - LAN/: R: Fast BSS.
課務組 Curriculum Section
创建型设计模式.
软件建模精要 面向对象软件建模技术.
類別(class) 類別class與物件object.
C 語言簡介 - 2.
第9章 類別圖與物件圖 9-1 類別圖與物件圖的基礎 9-2 類別圖的符號 9-3 類別關係 9-4 物件圖 9-5 繪製類別圖與物件圖
2D / 3D 遊戲程式設計入門 使用 XNA 3.0 與 C# 2D圖形與字型的呈現.
Methods 靜宜大學資工系 蔡奇偉副教授 ©2011.
第三章 基本觀念 電腦繪圖與動畫 (Computer Graphics & Animation) Object Data Image
SPOTO TM JAVA课程 JAVA中的OO语法
第三章 项目设定.
2D / 3D 遊戲程式設計入門 使用 XNA 3.0 與 C# 第五章 頂點定義與基本形狀的繪出.
Visual Basic 物件導向程式設計簡介.
Interval Estimation區間估計
SpringerLink 新平台介绍.
ICG 2018 Fall Homework1 Guidance
句子成分的省略(1).
第一單元 建立java 程式.
第三章 基本觀念 電腦繪圖與動畫 (Computer Graphics & Animation) Object Data Image
Chapter 9 (三维几何变换) To Discuss The Methods for Performing Geometric Transformations.
Chapter 5 Recursion.
Microsoft SQL Server 2008 報表服務_設計
Ch20. 計算器 (Mac 版本).
Unity LAB 2D UFO Tutorial
Guide to a successful PowerPoint design – simple is best
Chapter 5 Attributes of Output Primitives (图元的属性)
3.5 Region Filling Region Filling is a process of “coloring in” a definite image area or region. 2019/4/19.
GridView.
SpringerLink 新平台介绍.
Class & Object 靜宜大學資工系 蔡奇偉副教授 ©2011.
Inheritance -II.
Interfaces and Packages
Object-Oriented Programming in C++ 第二章 类和对象
Distance Vector vs Link State
2D / 3D 遊戲程式設計入門 使用 XNA 3.0 與 C# 第三章 XNA 遊戲程式基本架構.
Video 影像 (VideoPlayer 影像播放器、Camcorder 錄影機) 靜宜大學資管系 楊子青
Create and Use the Authorization Objects in ABAP
C++语言程序设计 C++语言程序设计 第八章 继承 C++语言程序设计.
Ch03 Layout.
進階UI元件:ListView元件以及複選 靜宜大學資管系 楊子青
反覆迴圈、陣列、副程式 靜宜大學資管系 楊子青
反覆迴圈、陣列、副程式 靜宜大學資管系 楊子青
Distance Vector vs Link State Routing Protocols
怎樣把同一評估 給與在不同班級的學生 How to administer the Same assessment to students from Different classes and groups.
Activity的生命週期: 播放音樂與影片 靜宜大學資管系 楊子青
MGT 213 System Management Server的昨天,今天和明天
Introduction to Computer Security and Cryptography
SQLite資料庫 靜宜大學資管系 楊子青.
Principle and application of optical information technology
Develop and Build Drives by Visual C++ IDE
InputStreamReader Console Scanner
When using opening and closing presentation slides, use the masterbrand logo at the correct size and in the right position. This slide meets both needs.
Presentation transcript:

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

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

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.

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

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

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

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

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

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

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

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

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

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.

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

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

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。

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.

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.

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

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

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

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

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.

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

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).

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

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

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

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

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

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);

執行結果

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

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, 1, SpriteEffects.None, 0); spriteBatch.End(); base.Draw(gameTime); }

執行結果

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

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), 0.5f); // 中 DrawSprite(sprite2, new Vector2(xoffset+75, 175), 0 ); // 前 DrawSprite(sprite3, new Vector2(xoffset+150, 250), 1 ); // 後

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

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

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

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

新增這一項

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

<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>

字型名稱

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

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

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

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

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

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

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

顯示中文字 把程式用到的所有中文字,按照左圖所示的格式加進字型描述檔中。 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();

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

SpriteFont Class

SpriteBatch.DrawString() 方法