25 / 25 / 5
Регистрация: 11.11.2009
Сообщений: 56
1

Вывод графических примитивов на XNA

04.03.2011, 07:35. Показов 4397. Ответов 9
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Как на XNA выводить на экран примитивы линию или полосу?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
04.03.2011, 07:35
Ответы с готовыми решениями:

Рисование геометрических примитивов в XNA
Здравствуйте! Как мне нарисовать линию, квадрат(или полигон), круг и вывести строку в XNA? Можешь...

Хранение, вывод и изменение графических примитивов
Здравствуйте! Помогите новичку организовать хранение, вывод и изменение графических примитивов....

Вывод текста и графических примитивов на экран компьютера
выводит текст и квадрат на экран компа может кому понадобится, ибо в основном пишут как вывести...

Вывод графических примитивов в консольное окно посредством загрузки в консоль bmp изображения
Добрый день! Хочу "написать" код для вывода графических примитивов в консольное окно посредством...

9
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
04.03.2011, 09:23 2
C#
1
2
3
4
5
6
device.Clear(/**/);
Sprite sprite = new Sprite(device); // что-бы не выделять каждый раз новую область памяти,
// лучше завести статический обьект
sprite.BeginDraw();
sprite.DrawLine(/**/);
sprite.EndDraw();
Классы вы знаете, дальше гугл в руки.
0
25 / 25 / 5
Регистрация: 11.11.2009
Сообщений: 56
04.03.2011, 10:23  [ТС] 3
Цитата Сообщение от outoftime Посмотреть сообщение
C#
1
2
3
4
5
6
device.Clear(/**/);
Sprite sprite = new Sprite(device); // что-бы не выделять каждый раз новую область памяти,
// лучше завести статический обьект
sprite.BeginDraw();
sprite.DrawLine(/**/);
sprite.EndDraw();
Классы вы знаете, дальше гугл в руки.
Это для XNA 3.1? В 4.0 нет Sprite, есть только SpriteBatch.
0
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
04.03.2011, 15:37 4
C#
1
2
3
4
5
6
7
8
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
 
            // TODO: use this.Content to load your game content here
 
        }
C#
1
2
3
4
5
6
7
8
9
10
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
 
            // TODO: Add your drawing code here
            this.spriteBatch.Begin();
            this.spriteBatch.End();
 
            base.Draw(gameTime);
        }
Неужели сложно было самому догадаться?
0
25 / 25 / 5
Регистрация: 11.11.2009
Сообщений: 56
05.03.2011, 12:01  [ТС] 5
Догадаться не реально, т.к. у объекта spriteBatch класса SpriteBatch нет метода DrawLine
0
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
05.03.2011, 15:02 6
Тогда извиняюсь за грубость, я сам сегодня искал это, мне надо было зарисовать прямоугольник, смотри, может что-то поможет, лень вырезать, смотри весь код: LoadContent и Draw, переменные не очень важны #region Variables можешь спрятать.
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
 
namespace Sea_War.Core
{
    public class Button : Actor
    {
        #region Variables
        private Color textCurrentColor,
            textActiveColor,
            textNormalColor;
        public Color TextColor
        { 
            get { return textNormalColor; } 
            set 
            {
                textNormalColor = value;
            }
        }
        public Color TextColorActive
        {
            get { return textActiveColor; }
            set { textActiveColor = value; }
        }
        private Color _bacgroundColorNormal,
            _bacgroundColorActive,
            _bacgroundColorCurrent;
        public Color BackgroundColor
        {
            get { return _bacgroundColorNormal; }
            set { _bacgroundColorNormal = value; }
        }
        public Color BacgroundColorActive
        {
            get { return _bacgroundColorActive; }
            set { _bacgroundColorActive = value; }
        }
        private String _Text;
        public String Text 
        {
            get { return _Text; }
            set 
            {
                _Text = value;
                if (Rectangle != null && Font != null && AutoSize)
                {
                    Vector2 size = Font.MeasureString(Text);
                    if (Rectangle.Width < size.X || Rectangle.Height < size.Y)
                    {
                        Rectangle = new Rectangle(Rectangle.X, Rectangle.Y,
                            (int)Math.Max(Rectangle.Width, size.X),
                            (int)Math.Max(Rectangle.Height, size.Y));
                    }
                }
            }
        }
        private SpriteFont _Font;
        public SpriteFont Font
        {
            get { return _Font; } 
            set 
            {
                _Font = value;
                if (Text != null && Rectangle != null && AutoSize)
                {
                    Vector2 size = Font.MeasureString(Text);
                    if (Rectangle.Width < size.X || Rectangle.Height < size.Y)
                    {
                        Rectangle = new Rectangle(Rectangle.X, Rectangle.Y,
                            (int)Math.Max(Rectangle.Width, size.X),
                            (int)Math.Max(Rectangle.Height, size.Y));
                    }
                }
            } 
        }
        private Texture2D backgroundTexture;
 
        public Texture2D NormalTexture,
            HoverTexture;
        private Rectangle _Rectangle;
        public Rectangle Rectangle
        {
            get { return _Rectangle; }
            set
            { 
                _Rectangle = value;
                if (Text != null && Font != null && AutoSize)
                {
                    Vector2 size = Font.MeasureString(Text);
                    if (Rectangle.Width < size.X || Rectangle.Height < size.Y)
                    {
                        Rectangle = new Rectangle(Rectangle.X, Rectangle.Y,
                            (int)Math.Max(Rectangle.Width, size.X),
                            (int)Math.Max(Rectangle.Height, size.Y));
                    }
                }
                Location = new Vector2(_Rectangle.X, _Rectangle.Y);
                Width = _Rectangle.Width;
                Height = _Rectangle.Height;
            }
        }
        public bool AutoSize { get; set; }
        #endregion
 
        public Button(Game game)
            : base(game)
        {
            this.Initialize();
        }
 
        protected override void LoadContent()
        {
            base.LoadContent();
            backgroundTexture = new Texture2D(GraphicsDevice, 1, 1);
            backgroundTexture.SetData(new Color[] { Color.White });
        }
 
        public override void Initialize()
        {
            base.Initialize();
            AutoSize = true;
            textNormalColor = Color.Black;
            textActiveColor = Color.Green;
            textCurrentColor = textNormalColor;
        }
 
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            textCurrentColor = isMouseOver ? textActiveColor : textNormalColor;
        }
 
        public override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin();
            if (NormalTexture != null && HoverTexture != null)
            {
                if (isMouseOver)
                {
                    spriteBatch.Draw(HoverTexture, Rectangle, Color.White);
                }
                else
                {
                    spriteBatch.Draw(NormalTexture, Rectangle, Color.White);
                }
            }
            else
            {
                spriteBatch.Draw(backgroundTexture, Rectangle, BackgroundColor); /// прямоугольник
                spriteBatch.DrawString(Font, Text, Location, textCurrentColor);
            }
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
Добавлено через 16 секунд
Тогда извиняюсь за грубость, я сам сегодня искал это, мне надо было зарисовать прямоугольник, смотри, может что-то поможет, лень вырезать, смотри весь код: LoadContent и Draw, переменные не очень важны #region Variables можешь спрятать.
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
 
namespace Sea_War.Core
{
    public class Button : Actor
    {
        #region Variables
        private Color textCurrentColor,
            textActiveColor,
            textNormalColor;
        public Color TextColor
        { 
            get { return textNormalColor; } 
            set 
            {
                textNormalColor = value;
            }
        }
        public Color TextColorActive
        {
            get { return textActiveColor; }
            set { textActiveColor = value; }
        }
        private Color _bacgroundColorNormal,
            _bacgroundColorActive,
            _bacgroundColorCurrent;
        public Color BackgroundColor
        {
            get { return _bacgroundColorNormal; }
            set { _bacgroundColorNormal = value; }
        }
        public Color BacgroundColorActive
        {
            get { return _bacgroundColorActive; }
            set { _bacgroundColorActive = value; }
        }
        private String _Text;
        public String Text 
        {
            get { return _Text; }
            set 
            {
                _Text = value;
                if (Rectangle != null && Font != null && AutoSize)
                {
                    Vector2 size = Font.MeasureString(Text);
                    if (Rectangle.Width < size.X || Rectangle.Height < size.Y)
                    {
                        Rectangle = new Rectangle(Rectangle.X, Rectangle.Y,
                            (int)Math.Max(Rectangle.Width, size.X),
                            (int)Math.Max(Rectangle.Height, size.Y));
                    }
                }
            }
        }
        private SpriteFont _Font;
        public SpriteFont Font
        {
            get { return _Font; } 
            set 
            {
                _Font = value;
                if (Text != null && Rectangle != null && AutoSize)
                {
                    Vector2 size = Font.MeasureString(Text);
                    if (Rectangle.Width < size.X || Rectangle.Height < size.Y)
                    {
                        Rectangle = new Rectangle(Rectangle.X, Rectangle.Y,
                            (int)Math.Max(Rectangle.Width, size.X),
                            (int)Math.Max(Rectangle.Height, size.Y));
                    }
                }
            } 
        }
        private Texture2D backgroundTexture;
 
        public Texture2D NormalTexture,
            HoverTexture;
        private Rectangle _Rectangle;
        public Rectangle Rectangle
        {
            get { return _Rectangle; }
            set
            { 
                _Rectangle = value;
                if (Text != null && Font != null && AutoSize)
                {
                    Vector2 size = Font.MeasureString(Text);
                    if (Rectangle.Width < size.X || Rectangle.Height < size.Y)
                    {
                        Rectangle = new Rectangle(Rectangle.X, Rectangle.Y,
                            (int)Math.Max(Rectangle.Width, size.X),
                            (int)Math.Max(Rectangle.Height, size.Y));
                    }
                }
                Location = new Vector2(_Rectangle.X, _Rectangle.Y);
                Width = _Rectangle.Width;
                Height = _Rectangle.Height;
            }
        }
        public bool AutoSize { get; set; }
        #endregion
 
        public Button(Game game)
            : base(game)
        {
            this.Initialize();
        }
 
        protected override void LoadContent()
        {
            base.LoadContent();
            backgroundTexture = new Texture2D(GraphicsDevice, 1, 1);
            backgroundTexture.SetData(new Color[] { Color.White });
        }
 
        public override void Initialize()
        {
            base.Initialize();
            AutoSize = true;
            textNormalColor = Color.Black;
            textActiveColor = Color.Green;
            textCurrentColor = textNormalColor;
        }
 
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            textCurrentColor = isMouseOver ? textActiveColor : textNormalColor;
        }
 
        public override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin();
            if (NormalTexture != null && HoverTexture != null)
            {
                if (isMouseOver)
                {
                    spriteBatch.Draw(HoverTexture, Rectangle, Color.White);
                }
                else
                {
                    spriteBatch.Draw(NormalTexture, Rectangle, Color.White);
                }
            }
            else
            {
                spriteBatch.Draw(backgroundTexture, Rectangle, BackgroundColor); /// прямоугольник
                spriteBatch.DrawString(Font, Text, Location, textCurrentColor);
            }
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
Добавлено через 1 час 1 минуту
В прошлом посте я или сам написал свой спрайт, или юзал MDX сейчас разбираюсь.

Добавлено через 22 секунды
В прошлом посте я или сам написал свой спрайт, или юзал MDX сейчас разбираюсь.
0
1272 / 973 / 113
Регистрация: 12.01.2010
Сообщений: 1,971
06.03.2011, 17:22 7
Примитивы это популярная тема, много где спрашивают про них, обычно отсылают к GraphicsDevice.DrawUserPrimitives,
а это не совсем хороший вариант для новичка который хочет нарисовать простую линию из 2 точек

Мне самому нужны были примитивы еще со времен Как нарисовать прямоугольник выделения?

Вот чего сделал..
Код - умеет рисовать линию, прямоугольник(закрашивать умеет) и окружность
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    public class Primitive2D
    {
        private readonly GraphicsDevice _graphicsDevice;
 
        private Texture2D _circleTexture;
        private Texture2D _lineTexture;
 
        private Color _color;
        private int _lineWidth;
 
        #region constructors
 
        public Primitive2D( GraphicsDevice graphicsDevice, int lineWidth, Color lineColor )
        {
            if (graphicsDevice == null) throw new ArgumentNullException("graphicsDevice");
            if (lineWidth <= 0)
                lineWidth = 1;
 
            _graphicsDevice = graphicsDevice;
            _lineWidth = lineWidth;
            _color = lineColor;
 
            _lineTexture = CreateLineTexture(_graphicsDevice, _lineWidth, _color);
            _circleTexture = CreateCircleTexture(_graphicsDevice, 50, _color);
        }
 
        public Primitive2D( GraphicsDevice graphicsDevice, int lineWidth )
            : this(graphicsDevice, lineWidth, Color.Black)
        {
        }
 
        public Primitive2D( GraphicsDevice graphicsDevice )
            : this(graphicsDevice, 1, Color.Black)
        {
        }
 
        #endregion
 
        public Color Color
        {
            get { return _color; }
            set
            {
                if (_color != value)
                {
                    _color = value;
                    _lineTexture = CreateLineTexture(_graphicsDevice, _lineWidth, _color);
                    _circleTexture = CreateCircleTexture(_graphicsDevice, (int)CurrentCircleRadius, _color);
                }
            }
        }
 
        private float CurrentCircleRadius
        {
            get { return _circleTexture.Width / 2f; }
        }
 
        public int LineWidth
        {
            get { return _lineWidth; }
            set
            {
                if (value > 0 && _lineWidth != value)
                {
                    _lineWidth = value;
                    _lineTexture = CreateLineTexture(_graphicsDevice, _lineWidth, _color);
                }
            }
        }
 
 
        public void DrawLine( SpriteBatch spriteBatch, Vector2 startPos, Vector2 endPos )
        {
            float length;
            //MathEx.Distance(ref startPos, ref endPos, out length);
            Vector2.Distance(ref startPos, ref endPos, out length);
 
            Vector2 direct;
           // MathEx.Direction(ref startPos, ref endPos, out direct);
            Vector2.Subtract(ref endPos, ref startPos, out direct);
            direct.Normalize();
 
            float rotation = (float)Math.Atan2(direct.Y, direct.X); 
            //MathEx.AngleFromDirection(ref direct, out rotation);
 
            var rect = new Rectangle((int)startPos.X, (int)startPos.Y, (int)length, _lineWidth);
 
            spriteBatch.Draw(_lineTexture, rect, null, Color.White, rotation, Vector2.Zero, SpriteEffects.None, 0);
        }
 
        public void DrawRectangle( SpriteBatch spriteBatch, Rectangle rectangle, bool fill )
        {
            if (rectangle.Width < 0)
            {
                rectangle.X += rectangle.Width;
                rectangle.Width = -rectangle.Width;
            }
 
            if (rectangle.Height < 0)
            {
                rectangle.Y += rectangle.Height;
                rectangle.Height = -rectangle.Height;
            }
 
            Rectangle tempRect = rectangle;
 
            if (fill)
            {
                //если тощина линии больше рисуемого прямоугольника будут корявости, пофиксим  
                if (rectangle.Width < _lineWidth)
                    LineWidth = 1; //rectangle.Width; //хз как лучше, выглядит одинакого и фпс тот же
                if (rectangle.Height < _lineWidth)
                    LineWidth = 1; // rectangle.Height;
 
 
                tempRect.Height = _lineWidth;
                spriteBatch.Draw(_lineTexture, tempRect, Color.White);
 
                tempRect.Height += rectangle.Height - _lineWidth;
                spriteBatch.Draw(_lineTexture, tempRect, Color.White);
 
                tempRect = rectangle;
 
                tempRect.Width = _lineWidth;
                spriteBatch.Draw(_lineTexture, tempRect, Color.White);
 
                tempRect.Width += rectangle.Width - _lineWidth;
                spriteBatch.Draw(_lineTexture, tempRect, Color.White);
            }
            else
            {
                tempRect.Height = _lineWidth;
                spriteBatch.Draw(_lineTexture, tempRect, Color.White);
 
                tempRect.Y += rectangle.Height - _lineWidth;
                spriteBatch.Draw(_lineTexture, tempRect, Color.White);
 
                tempRect = rectangle;
 
                tempRect.Width = _lineWidth;
                spriteBatch.Draw(_lineTexture, tempRect, Color.White);
 
                tempRect.X += rectangle.Width - _lineWidth;
                spriteBatch.Draw(_lineTexture, tempRect, Color.White);
            }
        }
 
        public void DrawCircle( SpriteBatch spriteBatch, Vector2 center, int radius )
        {
            float scale = radius / CurrentCircleRadius;
 
            if (scale > 1.5f)
            {
                _circleTexture = CreateCircleTexture(_graphicsDevice, (int)(CurrentCircleRadius * 2), _color);
                scale = radius / CurrentCircleRadius;
            }
            else if (scale < 0.5f)
            {
                _circleTexture = CreateCircleTexture(_graphicsDevice, (int)(CurrentCircleRadius / 2), _color);
                scale = radius / CurrentCircleRadius;
            }
 
            var origin = new Vector2(radius / scale, radius / scale);
 
            spriteBatch.Draw(_circleTexture, center, null, Color.White, 0, origin, scale, SpriteEffects.None, 0);
        }
 
        public static Texture2D CreateLineTexture( GraphicsDevice device, int width, Color color )
        {
            var texture = new Texture2D(device, width, width);
 
            var colors = new Color[width * width];
 
            for (int i = 0; i < colors.Length; i++)
                colors[i] = color;
 
            texture.SetData(colors);
 
            return texture;
        }
 
        public static Texture2D CreateCircleTexture( GraphicsDevice device, int radius, Color color )
        {
            var texture = new Texture2D(device, ((radius << 1) + 1), ((radius << 1) + 1));
 
            var arrayWrap = new ArrayWrap<Color>(texture.Width, texture.Height);
 
            #region Алгоритм_Брезенхема
            int x0 = radius;
            int y0 = radius;
 
            int x = 0;
            int y = radius;
            int delta = 2 - radius << 1;
            while (y >= 0)
            {
                arrayWrap[x0 + x, y0 + y] = color;
                arrayWrap[x0 + x, y0 - y] = color;
                arrayWrap[x0 - x, y0 + y] = color;
                arrayWrap[x0 - x, y0 - y] = color;
 
                int error = ((delta + y) << 1) - 1;
                if (delta < 0 && error <= 0)
                {
                    ++x;
                    delta += (x << 1) + 1;
                    continue;
                }
                error = ((delta - x) << 1) - 1;
                if (delta > 0 && error > 0)
                {
                    --y;
                    delta += 1 - y << 1;
                    continue;
                }
                ++x;
                delta += (x - y) << 1;
                --y;
            }
            #endregion
 
            texture.SetData(arrayWrap.Source);
 
            return texture;
        }
 
 
        #region Nested type: ArrayWrap
 
        private class ArrayWrap<T>
        {
            private readonly T[] _source;
            private readonly int _x;
            private readonly int _y;
 
            public ArrayWrap( int x, int y )
            {
                _x = x;
                _y = y;
                _source = new T[x * y];
            }
 
            public T[] Source
            {
                get { return _source; }
            }
 
            public T this[int i]
            {
                get { return _source[i]; }
                set { _source[i] = value; }
            }
 
            public T this[int x, int y]
            {
                get
                {
                    if (x > _x || y > _y) throw new IndexOutOfRangeException();
                    return _source[y * _x + x];
                }
                set
                {
                    if (x > _x || y > _y) throw new IndexOutOfRangeException();
                    _source[y * _x + x] = value;
                }
            }
        }
 
        #endregion
 
        //         public void DrawTriangle( SpriteBatch spriteBatch, Vector2 point1, Vector2 point2, Vector2 point3 )
        //         {
        //             DrawLine(spriteBatch, point1, point2);
        //             DrawLine(spriteBatch, point2, point3);
        //             DrawLine(spriteBatch, point3, point1);
        //         }
    }
пользоваться совсем просто
C#
1
2
3
      Primitive2D primitive = new Primitive2D(GraphicsDevice);
...
            primitive.DrawLine(spriteBatch, точка1, точка2);


Вроде вполне быстро рисуется, конечно если не менять по 5 раз на кадр цвет и толщину линии(пересоздание текстуры)

Если кто-то знает более оптимальные варианты отрисовки с радостью приму код
От закрашенной окружности тоже не откажусь )
0
25 / 25 / 5
Регистрация: 11.11.2009
Сообщений: 56
10.03.2011, 06:17  [ТС] 8
С трудом нашел рабочий пример на XNA для рисования линии. Вроде убрал все лишнее, вот что получилось.
Инициализация
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
protected override void Initialize()
{
    // задаем размер экрана и применяем изменение
    _graphics.PreferredBackBufferWidth = 500;
    _graphics.PreferredBackBufferHeight = 500;
    _graphics.IsFullScreen = false;
    _graphics.ApplyChanges();
 
    // инициализация матрицы преобразования
    _projectionMatrix = Matrix.CreateOrthographicOffCenter(0,
        GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, // ширина и высота окна
        0, 0.0f, 1000.0f);
 
    // инициализация эффекта
    _basicEffect = new BasicEffect(GraphicsDevice);
    _basicEffect.VertexColorEnabled = true; // учитывать цвет точек
    _basicEffect.Projection = _projectionMatrix;
 
    base.Initialize();
}
Метод для рисования линии
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
/// <summary>
/// Рисует линию от positionColor1 к positionColor2
/// </summary>
/// <param name="positionColor1">Первая точка</param>
/// <param name="positionColor2">Вторая точка</param>
private void DrawLine(VertexPositionColor positionColor1, VertexPositionColor positionColor2)
{
    // Если нужно, то могу расписать назначения параметров
    GraphicsDevice.DrawUserIndexedPrimitives(
        PrimitiveType.LineList,
        new[] { positionColor1, positionColor2 },
        0, 2, new short[] { 0, 1 }, 0, 1);
}
Использование метода для рисования линии
C#
1
2
3
4
5
6
7
8
9
10
11
12
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.SteelBlue);
 
    foreach (EffectPass pass in _basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        DrawLine(new VertexPositionColor(new Vector3(1, 1, 0), Color.Red),
            new VertexPositionColor(new Vector3(500 - 1, 500 - 1, 0), Color.Red));
    }
    base.Draw(gameTime);
}
Код всего класса public class Game1 : Game
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
 
namespace WindowsGame2
{
    public class Game1 : Game
    {
        // похоже нужна для преобразования координат из экранных в другие
        Matrix _projectionMatrix;
        // что это еще не понял, но без него не работает
        BasicEffect _basicEffect;
 
        readonly GraphicsDeviceManager _graphics;
 
        public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }
 
        protected override void Initialize()
        {
            // задаем размер экрана и применяем изменение
            _graphics.PreferredBackBufferWidth = 500;
            _graphics.PreferredBackBufferHeight = 500;
            _graphics.IsFullScreen = false;
            _graphics.ApplyChanges();
 
            // инициализация матрицы преобразования
            _projectionMatrix = Matrix.CreateOrthographicOffCenter(0,
                GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, // ширина и высота окна
                0, 0.0f, 1000.0f);
 
            // инициализация эффекта
            _basicEffect = new BasicEffect(GraphicsDevice);
            _basicEffect.VertexColorEnabled = true; // учитывать цвет точек
            _basicEffect.Projection = _projectionMatrix;
 
            base.Initialize();
        }
 
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
 
            // TODO: use this.Content to load your game content here
        }
 
        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }
 
        protected override void Update(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();
            base.Update(gameTime);
        }
 
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.SteelBlue);
 
            foreach (EffectPass pass in _basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                DrawLine(new VertexPositionColor(new Vector3(1, 1, 0), Color.Red),
                    new VertexPositionColor(new Vector3(500 - 1, 500 - 1, 0), Color.Red));
            }
            base.Draw(gameTime);
        }
 
        /// <summary>
        /// Рисует линию от positionColor1 к positionColor2
        /// </summary>
        /// <param name="positionColor1">Первая точка</param>
        /// <param name="positionColor2">Вторая точка</param>
        private void DrawLine(VertexPositionColor positionColor1, VertexPositionColor positionColor2)
        {
            GraphicsDevice.DrawUserIndexedPrimitives(
                PrimitiveType.LineList,
                new[] { positionColor1, positionColor2 },
                0, 2, new short[] { 0, 1 }, 0, 1);
        }
    }
}
0
444 / 348 / 32
Регистрация: 16.10.2010
Сообщений: 842
Записей в блоге: 7
18.03.2011, 16:47 9
писал недавно с нулевыми знаниями о 3d за два дня, пришлось попотеть, так как примера построения линий и треугольников в 3d не находил нигде.

всё делаю через DrawUserPrimitives, и отрисовываю через базовый эффект, камеру можно вращать, число частиц можно увеличивать

Release za5.rar (.net 2.0 xna 3.1)
1
444 / 348 / 32
Регистрация: 16.10.2010
Сообщений: 842
Записей в блоге: 7
18.03.2011, 17:38 10
Цитата Сообщение от m0nax Посмотреть сообщение
Примитивы это популярная тема, много где спрашивают про них, обычно отсылают к GraphicsDevice.DrawUserPrimitives,
а это не совсем хороший вариант для новичка который хочет нарисовать простую линию из 2 точек
Мне самому нужны были примитивы еще со времен Как нарисовать прямоугольник выделения?Вроде вполне быстро рисуется, конечно если не менять по 5 раз на кадр цвет и толщину линии(пересоздание текстуры)Если кто-то знает более оптимальные варианты отрисовки с радостью приму код
От закрашенной окружности тоже не откажусь )
если их много... жестоко... в плане производительности примерно также, как рисовать на канве формы)
DrawUserPrimitives более разумно, закрашенная окружность тривиально рисуется через TriangleFan, можно в рантайме рисовать + эффект с прозрачностью приклеить можно
1
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
18.03.2011, 17:38
Помогаю со студенческими работами здесь

Использование графических примитивов
Добрый вечер уважаемые форумчане! Необходима ваша помощь в решении следующей задачи. Требуется...

Рисование графических примитивов
Приложение, которое читает данные из файла о координатах и размерах различных графических...

Построение графических примитивов
Ребята помогите пожалуйста нужно две программы вообщем задание такое :1) Построение графичнных...

Анимация графических примитивов
Всем привет. Передо мной стоит задача сделать простейшую анимацию 3-х овалов, но увы я никак не...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru