Esempio n. 1
0
        private unsafe Texture CreateTexture(TextKey key)
        {
            var size       = key.Size;
            var actualFont = key.Font;

            var image = _textImagePool.Acquire(new ImageKey
            {
                Width  = (int)Math.Ceiling(size.X),
                Height = (int)Math.Ceiling(size.Y)
            });

            // Clear image to transparent.
            // TODO: Don't need to do this for a newly created image.
            fixed(void *pin = &image.DangerousGetPinnableReferenceToPixelBuffer())
            {
                Unsafe.InitBlock(pin, 0, (uint)(image.Width * image.Height * 4));
            }

            image.Mutate(x =>
            {
                var location = new SixLabors.Primitives.PointF(0, size.Y / 2.0f);

                // TODO: Vertical centering is not working properly.
                location.Y *= 0.8f;

                var color = key.Color;

                x.DrawText(
                    new TextGraphicsOptions
                {
                    WrapTextWidth       = size.X,
                    HorizontalAlignment = key.Alignment == TextAlignment.Center
                            ? HorizontalAlignment.Center
                            : HorizontalAlignment.Left,
                    VerticalAlignment = VerticalAlignment.Center
                },
                    key.Text,
                    actualFont,
                    new Bgra32(
                        (byte)(color.R * 255.0f),
                        (byte)(color.G * 255.0f),
                        (byte)(color.B * 255.0f),
                        (byte)(color.A * 255.0f)),
                    location);
            });

            Texture texture;

            // Draw image to texture.
            fixed(void *pin = &image.DangerousGetPinnableReferenceToPixelBuffer())
            {
                texture = _graphicsDevice.ResourceFactory.CreateTexture(
                    TextureDescription.Texture2D(
                        (uint)image.Width,
                        (uint)image.Height,
                        1,
                        1,
                        PixelFormat.B8_G8_R8_A8_UNorm,
                        TextureUsage.Sampled));

                _graphicsDevice.UpdateTexture(
                    texture,
                    new IntPtr(pin),
                    (uint)(image.Width * image.Height * 4),
                    0, 0, 0,
                    texture.Width,
                    texture.Height,
                    1,
                    0,
                    0);
            }

            _textImagePool.ReleaseAll();

            return(texture);
        }