c# – 如何绘制正方形边框?

前端之家收集整理的这篇文章主要介绍了c# – 如何绘制正方形边框?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用单声道(使用XNA API接口)写我的游戏.到目前为止,它是伟大的,但我已经打破了一些应该是简单的东西.

我需要画一个2d平方.但我只想要边框(不填).

我看到很多例子,显示如何做一个填补的.但是没有一个只会显示一个边界.

我想我可以做一个图像并使用它.但我怀疑它会调整好.

解决方法

我刚刚以这种方式创建了一个Texture2D的扩展方法
  1. static class Utilities {
  2. public static void CreateBorder( this Texture2D texture,int borderWidth,Color borderColor ) {
  3. Color[] colors = new Color[ texture.Width * texture.Height ];
  4.  
  5. for ( int x = 0; x < texture.Width; x++ ) {
  6. for ( int y = 0; y < texture.Height; y++ ) {
  7. bool colored = false;
  8. for ( int i = 0; i <= borderWidth; i++ ) {
  9. if ( x == i || y == i || x == texture.Width - 1 - i || y == texture.Height - 1 - i ) {
  10. colors[x + y * texture.Width] = borderColor;
  11. colored = true;
  12. break;
  13. }
  14. }
  15.  
  16. if(colored == false)
  17. colors[ x + y * texture.Width ] = Color.Transparent;
  18. }
  19. }
  20.  
  21. texture.SetData( colors );
  22. }
  23. }

然后我测试了:

  1. //...
  2.  
  3. protected override void Initialize( ) {
  4. // TODO: Add your initialization logic here
  5. square = new Texture2D( GraphicsDevice,100,100 );
  6. square.CreateBorder( 5,Color.Red );
  7.  
  8. base.Initialize( );
  9. }
  10.  
  11. //...
  12.  
  13. protected override void Draw( GameTime gameTime ) {
  14. GraphicsDevice.Clear( Color.CornflowerBlue );
  15.  
  16. // TODO: Add your drawing code here
  17. spriteBatch.Begin( );
  18. spriteBatch.Draw( square,new Vector2( 0.0f,0.0f ),Color.White );
  19. spriteBatch.End( );
  20.  
  21. base.Draw( gameTime );
  22. }

结果如下:

猜你在找的C#相关文章