Custom Made inputTextBox正在闪烁

时间:2014-06-02 19:29:22

标签: c# user-interface xna spritebatch rendertarget

我在使用XNA 4.0创建输入框时遇到了困难。

我已经可以在inputTextbox中绘制和输入文本,但是当我输入时,我发现了两个问题。

  1. 当我按下一把钥匙时,我想它会写很多次这个角色,但事实并非如此。我不知道为什么不这样做。
  2. 当我按下一个键时屏幕闪烁,我该如何解决?我已经试过翻过后备缓冲器或类似的东西,这不是解决方案
  3. 以下是属于文本框的代码:

        public TextboxInput(GraphicsDevice graphicsDevice, int width, SpriteFont font)
        {
            this.font = font;
            var fontMeasurements = font.MeasureString("dfgjlJL");
            var height = (int) fontMeasurements.Y;
            renderTarget = new RenderTarget2D(graphicsDevice, width, height);
            Text = new StringBuilder();
            this.graphicsDevice = graphicsDevice;
            spriteBatch = new SpriteBatch(graphicsDevice);
        }
    
        public void Update(GameTime gameTime)
        {
            if (!HasFocus)
            {
                return;
            }
            var keyboard = Keyboard.GetState();
            foreach (var key in keyboard.GetPressedKeys())
            {
                if (!lastKeyboard.IsKeyUp(key))
                {
                    continue;
                }
                if (key == Keys.Delete ||
                    key == Keys.Back)
                {
                    if (Text.Length == 0)
                    {
                        continue;
                    }
                    Text.Length--;
                    renderIsDirty = true;
                    continue;
                }
                char character;
                if (!characterByKey.TryGetValue(key, out character))
                {
                    continue;
                }
                if (keyboard.IsKeyDown(Keys.LeftShift) ||
                    keyboard.IsKeyDown(Keys.RightShift))
                {
                    character = Char.ToUpper(character);
                }
                Text.Append(character);
                renderIsDirty = true;
            }
    
            lastKeyboard = keyboard;
    
        }
    
        public void PreDraw()
        {
            if (!renderIsDirty)
            {
                return;
            }
            graphicsDevice.Clear(BackgroundColor);
    
            renderIsDirty = false;
            graphicsDevice.SetRenderTarget(renderTarget);
            spriteBatch.Begin();
            spriteBatch.DrawString(font, Text, Vector2.Zero, ForegroundColor);
            spriteBatch.End();
            graphicsDevice.SetRenderTargets(null);
        }
    
        public void Draw()
        {
            spriteBatch.Begin();
            spriteBatch.Draw(renderTarget, Position, Color.White);
            spriteBatch.End();
        }
    

1 个答案:

答案 0 :(得分:1)

对于闪烁,我认为你应该在draw方法中调用graphicsDevice.Clear(BackgroundColor)。

以下代码是您在按住时不会获得更多字符的原因。它只是说如果按键上次状态已经启动,则只注册按键。

if (!lastKeyboard.IsKeyUp(key))
{
    continue;
}