You need to pack 8 pixels into a single byte for 1 bit color format. The inner loop would look like this:
var
bm: TBitmap;
i, j: Integer;
dest: ^Byte;
b: Byte;
bitsSet: Integer;
begin
bm := TBitmap.Create;
Try
bm.PixelFormat := pf1bit;
bm.SetSize(63, 30);
for i := 0 to bm.Height-1 do begin
b := 0;
bitsSet := 0;
dest := bm.Scanline[i];
for j := 0 to bm.Width-1 do begin
b := b shl 1;
if odd(i+j) then
b := b or 1;
inc(bitsSet);
if bitsSet=8 then begin
dest^ := b;
inc(dest);
b := 0;
bitsSet := 0;
end;
end;
if b<>0 then
dest^ := b shl (8-bitsSet);
end;
bm.SaveToFile('c:\desktop\out.bmp');
Finally
bm.Free;
End;
end;
The output looks like this:

Update
Rob's comment prompted me to look at using Pixels[]
rather than the bit-twiddling above. And indeed it is perfectly possible.
var
bm: TBitmap;
i, j: Integer;
Color: TColor;
begin
bm := TBitmap.Create;
Try
bm.PixelFormat := pf1bit;
bm.SetSize(63, 30);
for i := 0 to bm.Height-1 do begin
for j := 0 to bm.Width-1 do begin
if odd(i+j) then begin
Color := clBlack;
end else begin
Color := clWhite;
end;
bm.Canvas.Pixels[j,i] := Color;
end;
end;
bm.SaveToFile('c:\desktop\out.bmp');
Finally
bm.Free;
End;
end;
Since each call to assign Pixels[]
results in a call to the Windows API function SetPixel
, the bit-twiddling code would perform better. Of course, that would only ever matter if your bitmap creation code was a performance hot-spot.