ActionScript 3: Resizing image inside UIComponent
I have a UIComponent and inside it I put a loader (which loads an image file).
THE PROBLEM: Even though I resize the UIComponent(to a square), it will still follow the size of the image in the loader. But when I resize the image in the loader, it will become stretched. What I want to do is have a container(UIComponent) that has a fixed square size and after the image has been loaded it will ju开发者_如何转开发st fit in the dimention of the container without being stretched. Can anyone help me how to do that?
I've long been using this function to resize an image while preserving the aspect ratio:
public function constraintResize(iSourceWidth:*, iSourceHeight:*, iTargetWidth:*, iTargetHeight:*, iFitSmallerDimension:*):* {
if (iFitSmallerDimension == undefined) iFitSmallerDimension = false;
if (iTargetWidth == 0 || iTargetHeight == 0) return;
if (iSourceWidth == 0 || iSourceHeight == 0) return;
var newWidth:*;
var newHeight:*;
var targetRatio:*;
var sourceRatio:*;
var output:* = { width:iSourceWidth, height:iSourceHeight };
if (iSourceWidth <= iTargetWidth && iSourceHeight <= iTargetHeight) {
if (iFitSmallerDimension) {
targetRatio = iTargetWidth / iTargetHeight;
sourceRatio = iSourceWidth / iSourceHeight;
if (sourceRatio < targetRatio) {
newHeight = iTargetHeight;
newWidth = newHeight * sourceRatio;
} else {
newWidth = iTargetWidth;
newHeight = newWidth / sourceRatio;
}
output.width = newWidth
output.height = newHeight
}
} else {
targetRatio = iTargetWidth / iTargetHeight
sourceRatio = iSourceWidth / iSourceHeight
if (sourceRatio < targetRatio) {
newHeight = iTargetHeight
newWidth = newHeight * sourceRatio
} else {
newWidth = iTargetWidth
newHeight = newWidth / sourceRatio
}
output.width = newWidth
output.height = newHeight
}
return output
}
The function will give you the ideal dimensions to fit source
within target
. So, in your case, you can use it that way:
var s:* = constraintResize(loader.contentWidth, loader.contentHeight, yourSquare.width, yourSquare.height);
loader.width = s.width;
loader.height = s.height;
use UILoader component and set scaleContent=true in component inspector wondow.
精彩评论