相关函数: GetWindowOrgEx、SetViewportOrgEx(设置视口坐标原点)、SetViewportOrgEx

本例效果图:




代码文件:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    ScrollBar1: TScrollBar;
    ScrollBar2: TScrollBar;
    procedure FormCreate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormPaint(Sender: TObject);
    procedure ScrollBar1Change(Sender: TObject);
    procedure ScrollBar2Change(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var
  cvs: TCanvas;
  bit: TBitmap;

procedure TForm1.FormCreate(Sender: TObject);
begin
  bit := TBitmap.Create;
  bit.LoadFromFile('c:\temp\test.bmp');
  cvs := TCanvas.Create;
  cvs.Handle := GetDC(Handle);

  ScrollBar1.Align := alBottom;
  ScrollBar1.Max := ClientWidth - bit.Width;
  ScrollBar1.LargeChange := 16;

  ScrollBar2.Kind := sbVertical;
  ScrollBar2.Align := alRight;
  ScrollBar2.Max := ClientHeight - bit.Height;
  ScrollBar2.LargeChange := 16;
end;

procedure TForm1.FormShow(Sender: TObject);
begin
  ScrollBar1.Position := ScrollBar1.Max div 2;
  ScrollBar2.Position := ScrollBar2.Max div 2;
end;

procedure TForm1.FormPaint(Sender: TObject);
const
  str = 'Delphi';
var
  x,y: Integer;
begin
  {在图片中绘制文本}
  bit.Canvas.Font.Size := 24;
  bit.Canvas.Font.Style := [fsBold];
  bit.Canvas.Font.Color := clWhite;
  bit.Canvas.Brush.Style := bsClear;
  x := (bit.Width - bit.Canvas.TextWidth(str)) div 2;
  y := (bit.Height - bit.Canvas.TextHeight(str)) div 2 + 32;
  bit.Canvas.TextOut(x, y, str);

  {在窗体上绘制图片}
  x := ClientWidth - bit.Width;
  y := ClientHeight - bit.Height;
  cvs.Draw(x, y, bit);
end;

procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  {关键代码: 调整窗口坐标原点}
  SetWindowOrgEx(cvs.Handle, ScrollBar1.Position, ScrollBar2.Position, nil);
  Repaint;
end;

procedure TForm1.ScrollBar2Change(Sender: TObject);
begin
  ScrollBar1Change(Sender);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  bit.Free;
  cvs.Free;
end;

end.
窗体文件:
object Form1: TForm1
  Left = 212
  Top = 116
  Caption = 'Form1'
  ClientHeight = 204
  ClientWidth = 262
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  Position = poDesigned
  OnCreate = FormCreate
  OnDestroy = FormDestroy
  OnPaint = FormPaint
  OnShow = FormShow
  PixelsPerInch = 96
  TextHeight = 13
  object ScrollBar1: TScrollBar
    Left = 80
    Top = 80
    Width = 121
    Height = 17
    PageSize = 0
    TabOrder = 0
    OnChange = ScrollBar1Change
  end
  object ScrollBar2: TScrollBar
    Left = 80
    Top = 120
    Width = 121
    Height = 17
    PageSize = 0
    TabOrder = 1
    OnChange = ScrollBar2Change
  end
end