Click here to Skip to main content
15,890,947 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
C++
CBitmap bitmap;

bitmap.Attach(image.Detach());

HBITMAP hBitmap6 = (HBITMAP)bitmap.GetSafeHandle();

m_Btn1.SetBitmap(hBitmap6);
but image isn't proportionate to size of button

but image of CButton isn't proportionate to size of my button

What I have tried:

C++
m_Btn1.ShowWindow(SW_SHOW);
m_Btn1.ModifyStyle(0, BS_BITMAP);

CImage image;
HRESULT hr = image.Load(str_path); // just change extension to load jpg

CImageList *pImage;

CBitmap bitmap;

bitmap.Attach(image.Detach());

HBITMAP hBitmap6 = (HBITMAP)bitmap.GetSafeHandle();

BUTTON_IMAGELIST *lst;

pImage = new CImageList;
lst = new BUTTON_IMAGELIST;

pImage->Create(20, 20, ILC_COLOR8, 20, 20);
pImage->Add(&bitmap, RGB(0, 0, 0));

HICON hicon = pImage->ExtractIcon(0);
ICONINFOEX iinfo;
iinfo.cbSize = sizeof(ICONINFOEX);
GetIconInfoEx(hicon, &iinfo);

m_Btn1.SetBitmap(iinfo.hbmColor);
Posted
Updated 22-Apr-24 20:32pm
v4
Comments
Member 14594285 22-Apr-24 12:02pm    
I solved, thanks
jeron1 22-Apr-24 13:15pm    
Great! Perhaps you could flag this thread as 'answered'.
Member 14594285 23-Apr-24 4:21am    
I can't because your answer in in the comments

1 solution

To display an image with the correct aspect ratio on a button, you must first calculate a common scaling factor, rescale the image with it and finally crop it. The following function performs these steps. The image can be a file or a resource e.g. in jpg format. I have tested the function with an image that is larger than the button.
C++
void RezizeImage(CImage& img_src, CImage& img_dst, int dstW, int dstH)
{
img_dst.Create(dstW, dstH, 32);

HDC hdc_src = img_src.GetDC();
HDC hdc_dst = img_dst.GetDC();
if (!hdc_src || !hdc_dst) // check dcs
return;

int srcW = img_src.GetWidth();
int srcH = img_src.GetHeight();

// calc scale
double s = max((double)dstW / srcW, (double)dstH / srcH);
srcW *= s; srcH *= s;

// calc ofset
int ofsH=0, ofsW = 0;
if (srcH != dstH) 
	ofsH = (dstH - srcH) / 2;
else
	ofsW = (dstW - srcW) / 2;

SetStretchBltMode(hdc_src, COLORONCOLOR);
SetStretchBltMode(hdc_dst, COLORONCOLOR);
img_src.StretchBlt(hdc_src, 0, 0, srcW, srcH, SRCCOPY);  // resize
img_src.BitBlt(hdc_dst, ofsW, ofsH, SRCCOPY);       // crop

img_src.ReleaseDC();
img_dst.ReleaseDC();
}

It may also be possible to optimize the program.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900