using SkiaSharp;
namespace Sandbox;
public partial class Bitmap
{
///
/// Rotates the bitmap by the specified angle.
///
/// The angle in degrees to rotate the bitmap.
/// A new instance with the rotated image.
public Bitmap Rotate( float degrees )
{
float sin = (float)Math.Abs( Math.Sin( degrees.DegreeToRadian() ) );
float cos = (float)Math.Abs( Math.Cos( degrees.DegreeToRadian() ) );
var rw = (int)(cos * Width + sin * Height);
var rh = (int)(cos * Height + sin * Width);
var newBitmap = new SKBitmap( rw, rh, _bitmap.ColorType, _bitmap.AlphaType );
using ( var canvas = new SKCanvas( newBitmap ) )
{
canvas.Clear( SKColors.Transparent );
canvas.Translate( rw / 2f, rh / 2f );
canvas.RotateDegrees( degrees );
canvas.Translate( -Width / 2f, -Height / 2f );
canvas.DrawBitmap( _bitmap, 0, 0 );
}
return new Bitmap( newBitmap );
}
///
/// Resizes the bitmap to the specified dimensions and returns a new bitmap.
///
/// The new width of the bitmap.
/// The new height of the bitmap.
/// Resample smoothly. If false this will be nearest neighbour.
/// A new instance with the specified dimensions.
public Bitmap Resize( int newWidth, int newHeight, bool smooth = true )
{
if ( newWidth <= 0 || newHeight <= 0 )
throw new ArgumentOutOfRangeException( "Width and height must be greater than zero." );
var info = new SKImageInfo( newWidth, newHeight, _bitmap.ColorType, _bitmap.AlphaType );
var sampling = smooth ? new SKSamplingOptions( SKFilterMode.Linear, SKMipmapMode.Linear ) : SKSamplingOptions.Default;
var newBitmap = _bitmap.Resize( info, sampling );
return new Bitmap( newBitmap );
}
///
/// Flips the bitmap vertically.
///
/// A new instance with the flipped image.
public Bitmap FlipVertical()
{
var newBitmap = new SKBitmap( _bitmap.Width, _bitmap.Height, _bitmap.ColorType, _bitmap.AlphaType );
using ( var canvas = new SKCanvas( newBitmap ) )
{
canvas.Scale( 1, -1 ); // Flip vertically
canvas.Translate( 0, -_bitmap.Height ); // Adjust position
canvas.DrawBitmap( _bitmap, 0, 0 );
}
return new Bitmap( newBitmap );
}
///
/// Flips the bitmap horizontally.
///
/// A new instance with the flipped image.
public Bitmap FlipHorizontal()
{
var newBitmap = new SKBitmap( _bitmap.Width, _bitmap.Height, _bitmap.ColorType, _bitmap.AlphaType );
using ( var canvas = new SKCanvas( newBitmap ) )
{
canvas.Scale( -1, 1 ); // Flip horizontally
canvas.Translate( -_bitmap.Width, 0 ); // Adjust position
canvas.DrawBitmap( _bitmap, 0, 0 );
}
return new Bitmap( newBitmap );
}
///
/// Crops the bitmap to the specified rectangle.
///
/// The rectangle to crop to.
/// A new instance with the cropped image.
public Bitmap Crop( Rect rect )
{
var newBitmap = new SKBitmap( (int)rect.Width, (int)rect.Height, _bitmap.ColorType, _bitmap.AlphaType );
using ( var canvas = new SKCanvas( newBitmap ) )
{
var sourceRect = rect.ToSk();
var destRect = new SKRect( 0, 0, rect.Width, rect.Height );
canvas.DrawBitmap( _bitmap, sourceRect, destRect );
}
return new Bitmap( newBitmap );
}
}