调整位图周围的画布大小? [英] Resize the canvas around a bitmap?
问题描述
拍摄下图,我将用于以下示例:
当前未裁剪的尺寸为 96 x 71
我想说我想将画布的尺寸调整为 115 x 80
-然后生成的图像应为:
Lets say I wanted to resize the canvas to 115 x 80
- the resulting image should then be:
最后,如果我将其尺寸调整为比原始画布小的尺寸,例如 45 x 45
,输出将如下所示:
Finally if I resized it to a smaller size than the original canvas was, eg 45 x 45
the output would appear like so:
这是我到目前为止尝试过的:
procedure ResizeBitmapCanvas(Bitmap: TBitmap; H, W: Integer);
var
Bmp: TBitmap;
Source, Dest: TRect;
begin
Bmp := TBitmap.Create;
try
Source := Rect(0, 0, Bitmap.Width, Bitmap.Height);
Dest := Source;
Dest.Offset(Bitmap.Width div 2, Bitmap.Height div 2);
Bitmap.SetSize(W, H);
Bmp.Assign(Bitmap);
Bmp.Canvas.FillRect(Source);
Bmp.Canvas.CopyRect(Dest, Bitmap.Canvas, Source);
Bitmap.Assign(Bmp);
finally
Bmp.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ResizeBitmapCanvas(Image1.Picture.Bitmap, 110, 110);
end;
如果在加载到TImage的位图上尝试上述操作,则实际位图不会居中,画布确实会改变大小。
If you try the above on a bitmap loaded into a TImage the actual bitmap does not center, the canvas does change size however.
我为图像设置的属性是:
The properties I have set for the Image are:
Image1.AutoSize := True;
Image1.Center := True;
Image1.Stretch := False;
我认为这可能是 Dest.Offset(Bitmap.Width div 2,Bitmap.Height div 2);
需要看一下,以计算正确的中心位置?
I think it could be the line Dest.Offset(Bitmap.Width div 2, Bitmap.Height div 2);
which needs looking at, to calculate the correct center position?
代码已被改编/修改
如何调整包围位图的画布的大小,而又不拉伸位图? p>
How do I resize the canvas that surrounds a bitmap, but without stretching the bitmap?
推荐答案
我认为这是您要寻找的东西:
I think this is what you are looking for:
procedure ResizeBitmapCanvas(Bitmap: TBitmap; H, W: Integer; BackColor: TColor);
var
Bmp: TBitmap;
Source, Dest: TRect;
Xshift, Yshift: Integer;
begin
Xshift := (Bitmap.Width-W) div 2;
Yshift := (Bitmap.Height-H) div 2;
Source.Left := Max(0, Xshift);
Source.Top := Max(0, Yshift);
Source.Width := Min(W, Bitmap.Width);
Source.Height := Min(H, Bitmap.Height);
Dest.Left := Max(0, -Xshift);
Dest.Top := Max(0, -Yshift);
Dest.Width := Source.Width;
Dest.Height := Source.Height;
Bmp := TBitmap.Create;
try
Bmp.SetSize(W, H);
Bmp.Canvas.Brush.Style := bsSolid;
Bmp.Canvas.Brush.Color := BackColor;
Bmp.Canvas.FillRect(Rect(0, 0, W, H));
Bmp.Canvas.CopyRect(Dest, Bitmap.Canvas, Source);
Bitmap.Assign(Bmp);
finally
Bmp.Free;
end;
end;
我不记得XE是否支持设置 Width
和高度
的 TRect
。如果没有,则将代码更改为
I can't remember if XE supports setting Width
and Height
for a TRect
. If not then change the code to
Source.Right := Source.Left + Min(W, Bitmap.Width);
,依此类推。
这篇关于调整位图周围的画布大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!