マウスカーソルの座標を取得します。
ソースコード
ファイル名:MouseOnImageXY.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
ファイル名:MainWindow.xaml.cs
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
namespace MouseOnImageXY;
public partial class MainWindow : Window
{
private string _baseTitle;
public MainWindow()
{
InitializeComponent();
_baseTitle = this.Title;
}
// マウス座標を画像のピクセル座標に変換してタイトルに表示
private void Img_MouseMove(object sender, MouseEventArgs e)
{
if (Img1?.Source is not BitmapSource bmp) return;
// Image上のマウス位置(単位はDIP: 1/96 inch)
var p = e.GetPosition(Img1);
// 画像DPIに応じてDIP -> ピクセルへ変換
double sx = bmp.DpiX / 96.0;
double sy = bmp.DpiY / 96.0;
int px = (int)Math.Floor(p.X * sx);
int py = (int)Math.Floor(p.Y * sy);
// 範囲内にクランプ(スクロール端などで負値になる可能性対策)
px = Math.Max(0, Math.Min(px, bmp.PixelWidth - 1));
py = Math.Max(0, Math.Min(py, bmp.PixelHeight - 1));
this.Title = $"{_baseTitle} | ({px}, {py}) px [{bmp.PixelWidth}×{bmp.PixelHeight}px DPI {bmp.DpiX:0.#},{bmp.DpiY:0.#}]";
}
// 画像外に出たらタイトルを戻す
private void Img_MouseLeave(object sender, MouseEventArgs e)
{
this.Title = _baseTitle;
}
}
DIP(Device Independent Pixel)= 1/96インチ は固定値みたいです。
ファイル名:MainWindow.xaml
<Window x:Class="MouseOnImageXY.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MouseOnImageXY"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">
<Image x:Name="Img1"
Stretch="None"
SnapsToDevicePixels="True"
RenderOptions.BitmapScalingMode="NearestNeighbor"
MouseMove="Img_MouseMove"
MouseLeave="Img_MouseLeave"
Source="C:\Users\karet\Pictures\color-sampl2.png"/><!-- ここを任意のローカルファイルパスに変更してください -->
</ScrollViewer>
</Grid>
</Window>
コメント