OSDN Git Service

MediaSelectorのサムネイル画像の縦横比を維持する
authorKimura Youichi <kim.upsilon@bucyou.net>
Thu, 19 Jan 2023 00:13:51 +0000 (09:13 +0900)
committerKimura Youichi <kim.upsilon@bucyou.net>
Thu, 19 Jan 2023 01:18:51 +0000 (10:18 +0900)
OpenTween/MediaSelector.cs
OpenTween/MediaSelectorPanel.cs

index 9d9bad9..f70c1fb 100644 (file)
@@ -204,21 +204,38 @@ namespace OpenTween
 
         public void AddMediaItem(IMediaItem item)
         {
-            MemoryImage thumbnailImage;
-            try
-            {
-                thumbnailImage = item.CreateImage();
-            }
-            catch (InvalidImageException)
-            {
-                thumbnailImage = MemoryImage.CopyFromImage(Properties.Resources.MultiMediaImage);
-            }
-
             var id = item.Id.ToString();
+            var thumbnailImage = this.GenerateThumbnailImage(item);
             this.ThumbnailList.Add(id, thumbnailImage);
             this.MediaItems.Add(item);
         }
 
+        private MemoryImage GenerateThumbnailImage(IMediaItem item)
+        {
+            using var origImage = this.CreateMediaItemImage(item);
+            var origSize = origImage.Image.Size;
+            var thumbSize = this.ThumbnailList.ImageList.ImageSize;
+
+            using var bitmap = new Bitmap(thumbSize.Width, thumbSize.Height);
+
+            // 縦横比を維持したまま thumbSize に収まるサイズに縮小する
+            using (var g = Graphics.FromImage(bitmap))
+            {
+                var scale = Math.Min(
+                    (float)thumbSize.Width / origSize.Width,
+                    (float)thumbSize.Height / origSize.Height
+                );
+                var fitSize = new SizeF(origSize.Width * scale, origSize.Height * scale);
+                var pos = new PointF(
+                    x: (thumbSize.Width - fitSize.Width) / 2.0f,
+                    y: (thumbSize.Height - fitSize.Height) / 2.0f
+                );
+                g.DrawImage(origImage.Image, new RectangleF(pos, fitSize));
+            }
+
+            return MemoryImage.CopyFromImage(bitmap);
+        }
+
         public void ClearMediaItems()
         {
             this.SelectedMediaItemId = null;
index cefbe5d..a342a3b 100644 (file)
@@ -63,6 +63,7 @@ namespace OpenTween
             this.MediaListView.LargeImageList = this.Model.ThumbnailList.ImageList;
 
             var thumbnailWidth = 75 * this.DeviceDpi / 96;
+            this.Model.ThumbnailList.ImageList.ColorDepth = ColorDepth.Depth24Bit;
             this.Model.ThumbnailList.ImageList.ImageSize = new(thumbnailWidth, thumbnailWidth);
 
             this.Model.PropertyChanged +=