2017-07-04 18 views
0

我被困在派生自TShape的類中。TShape - Paint事件中的繪圖問題

Paint方法中,我使用Canvas繪製一個矩形。在表格中,我有一個TTrackBar,允許更改的LeftTop座標。

使用TTrackBar設置爲LeftTop的值不重要,矩形不會相應地移動。相反,當我通過代碼設置這些值時,矩形出現在正確的位置。

我編碼與德爾福10.1柏林FireMonkey應用程序在Windows 10

unit frmShapeStudy; 

interface 

type 
    tMy_Shape = class (tShape) 
    protected 
    procedure Paint; override; 
    public 
    constructor Create (aOwner: tComponent); override; 
    procedure Draw; 
    end; 

    tformShapeStudy = class (tForm) 
    trkBarLeft: TTrackBar; 
    trkBarTop: TTrackBar; 
    procedure FormCreate  (Sender: tObject); 
    procedure TrackBarChange (Sender: tObject); 
    end; 

var 
    formShapeStudy: tformShapeStudy; 

implementation 

{$R *.fmx} 

var 
    My_Shape : tMy_Shape; 
    lvShapeRect : tRectF ; 

procedure tformShapeStudy.FormCreate (Sender: tObject); 
begin 
    My_Shape := tMy_Shape.Create (Self); 
    with My_Shape do begin 
    Parent := Self; 
    TrackBarChange (Self); 
    end; 
end; 

procedure tformShapeStudy.TrackBarChange (Sender: TObject); 
begin 
    My_Shape.Draw; 
end; 

constructor tMy_Shape.Create (aOwner: tComponent); 
begin 
    inherited; 
    with lvShapeRect do begin 
     Left := Self.Left; 
     Top := Self.Top ; 
     Height := 20; 
     Width := 20; 
    end; 
end; 

procedure tBS_Shape.Draw; 
begin 
    l := formShapeStudy.trkBarLeft.Value; 
    t := formShapeStudy.trkBarTop .Value; 
    {`Left & Top` are set with `l & t` or with `120 & 150` 
    and tested separately, by commenting the propper code lines} 
    lvShapeRect.Left := l; // this does no work 
    lvShapeRect.Top := t; // this does no work 
    lvShapeRect.Left := 120; // this works 
    lvShapeRect.Top := 150; // this works 
    Repaint; 
end; 

procedure tMy_Shape.Paint; 
begin 
    inherited; 
    with Canvas do begin 
     Fill .Color := tAlphaColorRec.Aqua; 
     Stroke.Color := tAlphaColorRec.Blue; 
     BeginScene; 
     FillRect (lvShapeRect, 0, 0, Allcorners, 1, tCornerType.Bevel); 
     DrawRect (lvShapeRect, 0, 0, Allcorners, 1, tCornerType.Bevel); 
     EndScene; 
    end; 
end; 

end. 
+0

'ShapeRect'屬性是隻讀的,你不能修改它。每次訪問它時,都會返回一個臨時的'TRectF'。你的代碼正在修改那些臨時的'TRectF',它們沒有被分配回'TShape'。這就是矩形不移動的原因。 –

+0

@Remy。如果您沒有注意到,'ShapeRect'是在實現部分的開頭部分聲明的局部變量。我認爲這個聲明優先於'tShape'的'ShapeRect'屬性。無論如何,上面的代碼只是真實代碼的摘錄,其中該變量被聲明爲'lvShapeRect'('lv'意爲'局部變量'),因此它不會與'ShapeRect'屬性混淆。我將這個聲明重命名爲'lvShapeRect'。 – user2383818

+0

你能打印l和t的值嗎? – loki

回答

0

對不起夥計們!是否使用Left & Top而不是Position.X & Position.Y的舊習慣。我同意新的Position的方式來設置Left & Top,但它沒有任何意義,Embarcadero仍然提供此屬性,但他們在設置控制的Left & Top方面沒有任何意義。說它換句話說,因爲那些老樓盤仍然可用,就應該設置Left & Top性質相同Position.X & Position.Y,否則它會導致這樣的錯誤,在這裏你起誓要設置Left & Top,但控制不動。

正確的方法來設置Left & Top是:

Position.X := aLeft; 
Position.Y := aTop; 

除非Embarcadero公司改變了Left & Top屬性(至極的可能性很小)的行爲。