Glen Morse
Glen Morse

Reputation: 2593

How to dim out a GraphicControl

I have a TCard ( TGraphicControl component) and it has a property background (TPicture)

I would like to be able to dim out or darken the background. Thus if i can play the card in the game then its normal. If i can not play the card in the game then its darken out. I have tried putting Tcard.enabled :=false Like you would a button, but it does not dim it out or darken the image / background.

Also I could not find a alphablend property for TPicture as i thought this might help.

With what property or component would i need to get this effect?

Upvotes: 2

Views: 579

Answers (1)

NGLN
NGLN

Reputation: 43649

Handling Enabled

Following your example, the enabled state of TButton is drawn by Windows. For your own control, a visual reflection of a disabled state should be drawn by yourself. Within the overriden Paint routine this will simply mean:

if Enabled then
  // draw enabled
else
  // draw disabled;

The VCL takes care of handling a change of the Enabled property, since it calls Invalidate on the CM_ENABLEDCHANGED message.

Drawing dimmed

The most simple solution is to draw all that has to be drawn alphablended:

procedure TCard.Paint;
var
  Tmp: TBitmap;
  BlendFunc: TBlendFunction;
begin
  if Enabled then
    InternalPaint(Canvas)
  else
  begin
    Tmp := TBitmap.Create;
    try
      Tmp.SetSize(Width, Height);
      InternalPaint(Tmp.Canvas);
      BlendFunc.BlendOp := AC_SRC_OVER;
      BlendFunc.BlendFlags := 0;
      BlendFunc.SourceConstantAlpha := 80;
      BlendFunc.AlphaFormat := 0;
      WinApi.Windows.AlphaBlend(Canvas.Handle, 0, 0, Width, Height,
        Tmp.Canvas.Handle, 0, 0, Width, Height, BlendFunc);
    finally
      Tmp.Free;
    end;
  end;
end;

Wherein the InternalPaint routine does everything you are doing now, for example:

procedure TCard.InternalPaint(ACanvas: TCanvas);
var
  R: TRect;
begin
  R := ClientRect;
  ACanvas.Brush.Color := clGray;
  ACanvas.Rectangle(R);
  InflateRect(R, -7, -7);
  if (FPicture.Graphic <> nil) and (not FPicture.Graphic.Empty) then
    ACanvas.StretchDraw(R, FPicture.Graphic);
end;

All this with the following result:

screenshot

The SourceConstantAlpha factor (max 255) signifies by how much the temporarily bitmap is blended with the destination surface. The default color of the Canvas is the color of the Parent (assuming you do not interfere with erasing background or something), which is clBtnFace in the above image. If that destination is all white, then the bitmap is faded to white. If you would like a blending color or a darkened effect, then add these two lines before AlphaBlend:

  Canvas.Brush.Color := clBlack; //or clMaroon
  Canvas.FillRect(ClientRect);

screenshot 2

Upvotes: 9

Related Questions