.NET Framework ではない .NET 8.0 とか .NET 9.0 などでは Windows OS の GDI+ に依存する System.Drawing 名前空間のグラフィックス機能は Visual Studio のテンプレートで作るプロジェクトには含まれてないと思っていたのですが、Windows Forms アプリの場合は例外のようです。そのことを備忘録として書いておきます。

そもそも Windows Forms は Windows API(GDI/GDI+)をマネージコードでラップし、Windows のユーザーインターフェイス要素へのアクセスを提供するアプリケーションフレームワークということなので、System.Drawing 名前空間のグラフィックス機能が使えないということはあり得ず、特別な配慮がされているようです。
下は Visual Studio 2022 のテンプレートを使ってターゲットフレームワーク .NET 9.0 で作成した Windows Forms アプリのプロジェクトのサンプルコードです。
using ClassLibrary;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
PictureBox pictureBox1 = new();
PictureBox pictureBox2 = new();
Class1 classLibrary = new();
public Form1()
{
InitializeComponent();
pictureBox1.Size = new Size(210, 110);
this.Controls.Add(pictureBox1);
pictureBox1.Image = CreateBitmap();
pictureBox2.Size = new Size(210, 110);
pictureBox2.Location = new Point(0, 120);
this.Controls.Add(pictureBox2); ;
pictureBox2.Image = classLibrary.CreateBitmapAtRuntime();
}
// WinForms は Windows API(GDI/GDI+)をマネージコードでラップし、
// Windows のユーザーインターフェイス要素へのアクセスを提供するアプリ
// ケーションフレームワーク・・・ということなので、System.Drawing
// 名前空間のグラフィックス機能はデフォルトで使える設定になり、以下の
// コードは問題なく動く。NuGet の System.Drawing.Common は不要。
public Bitmap CreateBitmap()
{
Bitmap flag = new(200, 100);
Graphics flagGraphics = Graphics.FromImage(flag);
int blue = 0;
int white = 11;
while (white <= 100)
{
flagGraphics.FillRectangle(Brushes.Blue, 0, blue, 200, 10);
flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10);
blue += 20;
white += 20;
}
return flag;
}
}
}
上のコードの CreateBitmap メソッドで使っている System.Drawing 名前空間の Bitmap, Graphics, Brushes クラスはデフォルトで使える設定になっており、期待通り青白の横線が描画された Bitmap が生成されます。 この記事の一番上の画像の青白の旗が CreateBitmap メソッドで生成された Bitmap を PictureBox に表示したものです。
では、同じソリューションの中にクラスライブラリのプロジェクトを追加し、そこで上と同様に Bitmap, Graphics, Brushes クラスを使ったらどうなるでしょう?

その場合、Bitmap, Graphics, Brushes クラスを利用するためには、クラスライブラリのプロジェクトに NuGet パッケージ System.Drawing.Common をインストールする必要があります。

さらに、Visual Studio でプロジェクトのプロパティを開いて、Target OS を Windows に設定しないと警告 CA1416 が出ます。(#pragma warning disable CA1416 を追記して警告を抑制することもできますが)

クラスライブラリのコードも以下に参考に載せておきます。上の Form1 のコードでは、下のクラスライブラリを使って取得した Bitmap を PictureBox2 に表示しています。一番上の画像の赤白の旗がそれです。
namespace ClassLibrary
{
public class Class1
{
public Bitmap CreateBitmapAtRuntime()
{
Bitmap flag = new(200, 100);
Graphics flagGraphics = Graphics.FromImage(flag);
int red = 0;
int white = 11;
while (white <= 100)
{
flagGraphics.FillRectangle(Brushes.Red, 0, red, 200, 10);
flagGraphics.FillRectangle(Brushes.White, 0, white, 200, 10);
red += 20;
white += 20;
}
return flag;
}
}
}