Code set image does not respect size

Code set image does not respect size

m_benigno
Explorer Explorer
291 Views
2 Replies
Message 1 of 3

Code set image does not respect size

m_benigno
Explorer
Explorer

Hello, i am trying to change the icon of a ribbon button at runtime, even tho it works, it tries to display the icon as a 32x32 instead of 16x16, button is created via cui editor and set to SmallWithText,  and icon is set from a function called from a command like following:

            var ribbon = ComponentManager.Ribbon;
            var togglePipingModeButton = ribbon?.FindItem("TogglePipingModeButton", false) as RibbonButton;

            var isDarkTheme = Application.GetSystemVariable("COLORTHEME").ToString() == "0";
            var imageName = PipCmnApp.PipingCommonSettings.AdvancedPipingMode ? (isDarkTheme ? "advancedpipingmode_dark" : "advancedpipingmode_light") : (isDarkTheme ? "simplepipingmode_dark" : "simplepipingmode_light");
            var uri = new Uri($"pack://application:,,,/PipCmn;component/Resources/ribbon/{imageName}.ico", UriKind.Absolute);
            togglePipingModeButton.Size = RibbonItemSize.Standard;

            var image = new BitmapImage(uri);

            togglePipingModeButton.Image = image;
            togglePipingModeButton.Text = PipCmnApp.PipingCommonSettings.AdvancedPipingMode ? "Modalità Avanzata" : "Modalità Semplificata";

 
this does indeed change the icon as said before, but as said, only shows the top-left "quadrant" of the 32x icon instead of scaling it to 16x

tried this with both 16x png and 32x png and had the same result, tried switching to ico but nothing changed.

0 Likes
Accepted solutions (1)
292 Views
2 Replies
Replies (2)
Message 2 of 3

DYH_
Enthusiast
Enthusiast
Accepted solution

To manually adjust the size

Bitmap resizedBitmap = new Bitmap(originBitmap.GetThumbailImage(width,height,null,Intptr.zero);

The size is related to your screen's scale, meaning the  width & height must be multiplied by this scale factor to get the final size.

var scale = Graphics.FromHwnd(Application.MainWindow.Handle).DpiX/96f;

 then

var bi = new BitmapImage();
bi.BeginInit();
using var ms = new MemoryStream();
resizedBitMap.Save(ms,ImageFormat.Png);
ms.Seek(0,SeekOrigin.Begin);
bi.StreamSource = ms;
bi.CacheOption = BitmapCaccheOption.OnLoad;
bi.EndInit();
ribbonButton.Image = bi;

The code above was written without an IDE ,  if you spot any errors, feel free to tweak it a bit.

Message 3 of 3

m_benigno
Explorer
Explorer

It did indeed work, a shame tho that i have to manually adjust the size even tho the icon is already in the desired size.
Nonetheless thanks for the answer!