根据旋转的TextBox旋转光标

10 .net c# wpf rotation cursor

我有一个TextBox允许我的用户旋转的东西.但我喜欢的用户是将它们的Cursor旋转角度旋转到相同的角度TextBox.例如,如果它们旋转TextBox到28°,那么当Cursor进入该TextBoxCursor还应本身旋转到28°.

任何帮助都将非常感谢.

谢谢 :)

Ray*_*rns 9

您可以使用WinForms中的System.Drawing.Icon类和WPF的位图旋转功能来旋转光标.

这样做的方法是加载图标,将其转换为BitmapSource,使用Image和RenderTargetBitmap旋转它,将其转换回Icon,保存,最后更新使其成为的字节2,10和11.而不是.ico.

这是代码的样子:

public Cursor GetRotatedCursor(byte[] curFileBytes, double rotationAngle)
{
  // Load as Bitmap, convert to BitmapSource
  var origStream = new MemoryStream(curFileBytes);
  var origBitmap = new System.Drawing.Icon(origStream).ToBitmap();
  var origSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(origBitmap.GetHBitmap());

  // Construct rotated image
  var image = new Image
  {
    BitmapSource = origSource,
    RenderTransform = new RotateTransform(rotationAngle)
  };

  // Render rotated image to RenderTargetBitmap
  var width = origBitmap.Width;
  var height = origBitmap.Height;
  var resultSource = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
  resultSource.Render(image);

  // Convert to System.Drawing.Bitmap
  var pixels = new int[width*height];
  resultSource.CopyPixels(pixels, width, 0);
  var resultBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPargb);
  for(int y=0; y<height; y++)
    for(int x=0; x<width; x++)
      resultBitmap.SetPixel(x, y, Color.FromArgb(pixels[y*width+x]));

  // Save to .ico format
  var resultStream = new MemoryStream();
  new System.Drawing.Icon(resultBitmap.GetHIcon()).Save(resultStream);

  // Convert saved file into .cur format
  resultStream.Seek(2); resultStream.WriteByte(curFileBytes, 2, 1);
  resultStream.Seek(10); resultStream.WriteByte(curFileBytes, 10, 2);
  resultStream.Seek(0);

  // Construct Cursor
  return new Cursor(resultStream);
}
Run Code Online (Sandbox Code Playgroud)

如果你想避免循环,你可以用一小段usafe代码替换它来调用获取初始化数据的System.Drawing.Bitmap构造函数:

  fixed(int* bits = pixels)
  {
    resultBitmap = new System.Drawing.Bitmap(width, height, width, System.Drawing.Imaging.PixelFormat.Format32bppPargb, new IntPtr(bits));
  }
Run Code Online (Sandbox Code Playgroud)

每次TextBox旋转更改时,您都需要调用它.这可以通过旋转TextBox的代码完成,也可以通过绑定到TextBox旋转的值的PropertyChangedCallback完成.