保存和恢复Canvas-> Pen State

时间:2019-03-15 14:27:26

标签: c++builder

我试图保存Canvas-> Pen的当前状态然后还原它,但是它不起作用,并且所有GDI功能在还原后都使用新的笔

    TPen * OldPen, * newpen;
    OldPen = Canvas->Pen;
    newpen = new TPen;
    newpen->Color = clPurple;
    newpen->Width = 2;
    Canvas->Pen = newpen;
// draw with the new pen...
    Canvas->Pen = OldPen;
    delete newpen;

Oldpen从未恢复过,为什么?

1 个答案:

答案 0 :(得分:4)

您实际上并没有保存和恢复任何内容。

您只是将指针保存到TPen所拥有的内部Canvas对象中。然后,当您将新的TPen对象分配给Canvas->Pen属性时,根本就没有交换对象,您只是将属性值从newpen对象复制到{{1} }对象-Canvas->Pen指向的对象。然后,当您尝试“还原” oldpen时,您只是在将属性值从原始的(已修改的)oldpen复制回自身,这是无操作的。

要执行您要尝试的操作,需要复制TPen对象,然后将其复制回去,如下所示:

Canvas->Pen

或者,改用GDI内置的save + restore functionality

TPen *OldPen = new TPen;
OldPen->Assign(Canvas->Pen);
Canvas->Pen->Color = clPurple;
Canvas->Pen->Width = 2;
// draw with the new pen...
Canvas->Pen->Assign(OldPen);
delete OldPen;