Created
September 15, 2013 13:49
-
-
Save scorta/6570914 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private double CalculateConstraintScale(double rotation, int pixelWidth, int pixelHeight) | |
{ | |
double PiDiv180 = Math.PI / 180; | |
// Convert angle to radians for the math lib | |
double rotationRadians = rotation * PiDiv180; | |
// Centre is half the width and height | |
double width = pixelWidth / 2.0; | |
double height = pixelHeight / 2.0; | |
double radius = Math.Sqrt(width * width + height * height); | |
// Convert BR corner into polar coordinates | |
double angle = Math.Atan(height / width); | |
// Now create the matching BL corner in polar coordinates | |
double angle2 = Math.Atan(height / -width); | |
// Apply the rotation to the points | |
angle += rotationRadians; | |
angle2 += rotationRadians; | |
// Convert back to rectangular coordinate | |
double x = Math.Abs(radius * Math.Cos(angle)); | |
double y = Math.Abs(radius * Math.Sin(angle)); | |
double x2 = Math.Abs(radius * Math.Cos(angle2)); | |
double y2 = Math.Abs(radius * Math.Sin(angle2)); | |
// Find the largest extents in X & Y | |
x = Math.Max(x, x2); | |
y = Math.Max(y, y2); | |
// Find the largest change (pixel, not ratio) | |
double deltaX = x - width; | |
double deltaY = y - height; | |
// Return the ratio that will bring the largest change into the region | |
return (deltaX > deltaY) ? width / x : height / y; | |
} | |
private WriteableBitmap GenerateConstrainedBitmap(BitmapImage sourceImage, int pixelWidth, int pixelHeight, double rotation) | |
{ | |
double scale = CalculateConstraintScale(rotation, pixelWidth, pixelHeight); | |
// Create a transform to render the image rotated and scaled | |
var transform = new TransformGroup(); | |
var rt = new RotateTransform() | |
{ | |
Angle = rotation, | |
CenterX = (pixelWidth / 2.0), | |
CenterY = (pixelHeight / 2.0) | |
}; | |
transform.Children.Add(rt); | |
var st = new ScaleTransform() | |
{ | |
ScaleX = scale, | |
ScaleY = scale, | |
CenterX = (pixelWidth / 2.0), | |
CenterY = (pixelHeight / 2.0) | |
}; | |
transform.Children.Add(st); | |
// Resize to specified target size | |
var tempImage = new Image() | |
{ | |
Stretch = Stretch.Fill, | |
Width = pixelWidth, | |
Height = pixelHeight, | |
Source = sourceImage, | |
}; | |
tempImage.UpdateLayout(); | |
// Render to a writeable bitmap | |
var writeableBitmap = new WriteableBitmap(pixelWidth, pixelHeight); | |
writeableBitmap.Render(tempImage, transform); | |
writeableBitmap.Invalidate(); | |
return writeableBitmap; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment