画布%%in frame%没有框架%size

时间:2017-01-31 22:43:17

标签: canvas racket

我在球拍中创造了一个小蛇游戏,我试图展示边界。

我定义了一些constantes:

(define WIDTH 500)

(define HEIGHT 500)

(define BLK_SIZE 10)

所以,所有块都是50px的正方形。

我创建了一个框架%

(define frame 
  (new (class frame%
         (define/augment (on-close)
           (send timer stop)
           (printf "ending...\n"))
         (super-new))
       [label "Snake"]
       [width WIDTH]
       [height HEIGHT]))

和画布%

(define game-canvas%
  (class canvas%
    (define/override (on-char e)
      (case (send e get-key-code)
        [(left) (unless (eq? last-dir 'right)
                  (set! dir 'left))]
        [(right) (unless (eq? last-dir 'left)
                   (set! dir 'right))]
        [(up) (unless (eq? last-dir 'down)
                (set! dir 'up))]
        [(down) (unless (eq? last-dir 'up)
                  (set! dir 'down))]
        [else (void)]))

    (super-new)))
;...
(define game-canvas (new game-canvas% (parent frame)))

我定义了边框:

(define (create-border)
  (let (
        [nbr-block-x (/ WIDTH BLK_SIZE)]
        [nbr-block-y (/ HEIGHT BLK_SIZE)])
    (append
     (for/list ([x (in-range nbr-block-x)])
       (make-cell x 0))
     (for/list ([x (in-range nbr-block-x)])
       (make-cell x (sub1 nbr-block-x)))
     (for/list ([y (in-range nbr-block-y)])
       (make-cell 0 y))
     (for/list ([y (in-range nbr-block-y)])
       (make-cell (sub1 nbr-block-y) y)))))

(define borders (create-border))

最后我绘制了边框:

(define-struct cell (x y))

(define (real-world-coordinate elem)
  (make-cell
   (* BLK_SIZE (cell-x elem))
   (* BLK_SIZE (cell-y elem))))

(define (draw-list-of-square! dc square-list)
  (for-each (lambda (elem)
              (send dc draw-rectangle
                    (cell-x (real-world-coordinate elem))
                    (cell-y (real-world-coordinate elem))
                    BLK_SIZE
                    BLK_SIZE))
            square-list))

使用该代码,我除了在窗口中看到边框。 这是代码的结果(没有调整框架大小):

render

如您所见,右边界和下边界位于我的框架之外。

由于我将块从0绘制到(sub1 nbr-block-x)(49)(在像素490中),边框应该出现在我的框架中。

我已经检查了frame%和canvas%的文档。 Canvas%定义设置为0的边距和框架%定义borderspacing,它们也设置为 0

1 个答案:

答案 0 :(得分:1)

这可能现在为时已晚,但对其他人可能仍然有用。

您应该让框架自动适应画布,而不是相反:

#lang racket/gui

(define WIDTH 500)
(define HEIGHT 500)

(define frame (new frame% [label "Snake"])) ; no size is specified

(define game-canvas
  (new canvas% [parent frame]
       [min-width WIDTH]
       [min-height HEIGHT]
       [stretchable-width #f] ; To make sure the canvas' sizes stay constant even if the frame is resized with the mouse
       [stretchable-height #f]
       [paint-callback
        (λ(cv dc)
          (send dc set-background "yellow")
          (send dc clear)
          )]))

; Before being shown, the sizes are automatically adjusted.
(send frame show #t)

如果需要,还可以通过以下方式强制重新计算尺寸

(send frame reflow-container)

如果在显示框架后尺寸发生任何变化。