MPNowPlayingInfoCenter does not set player controls when running iOS app on macOS with M1 - avaudioplayer

I want to use iOS app on Mac with M1. It mainly works as intended in "Designed for iPad" mode, except player controls do not appear in control center as they are on iOS.
Here is the important part of the code that works perfect on iOS:
import AVFoundation
import MediaPlayer
class RemoteCommandHandler: NSObject {
static let shared = RemoteCommandHandler()
weak var delegate: MainVCDelegate?
private var player: AVAudioPlayer?
private let audioSession = AVAudioSession.sharedInstance()
private let commandCenter = MPRemoteCommandCenter.shared()
private var nowPlayingInfo = [String: Any]()
private var obs: NSKeyValueObservation?
func initPlayback() {
if obs == nil {
do {
try audioSession.setCategory(.playback, mode: .default, options: [])
try audioSession.setActive(true)
} catch {
//error
}
obs = audioSession.observe( \.outputVolume ) { avSession, _ in
self.delegate?.setVolume(avSession.outputVolume)
}
setupRemoteTransportControls()
if player == nil {
do {
try player = AVAudioPlayer(contentsOf:
URL(fileURLWithPath: Bundle.main.path(forResource: "TestTrack", ofType: "m4a")!))
player?.delegate = self
player?.volume = 0
player?.numberOfLoops = 1
} catch let error as NSError {
//error
}
}
}
}
func setupNowPlaying() {
nowPlayingInfo[MPMediaItemPropertyTitle] = TrackInfo.title.userFriendlyString()
nowPlayingInfo[MPMediaItemPropertyArtist] = TrackInfo.artist.userFriendlyString()
nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = TrackInfo.album.userFriendlyString()
let image = NowPlayingInfo.getArtwork()
var artwork: MPMediaItemArtwork
artwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = PlayerStatusInfo.isPlaying() ? 1 : 0
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = NowPlayingInfo.getDurationMs() / 1000
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = NowPlayingInfo.currentMs / 1000
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackProgress] = NowPlayingInfo.calculateProgress()
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
}
Would appreciate any suggestions on how to make it work on Mac.

Related

GWT read mime type client side

I'm trying to read the mime type in GWT client side in order to validate a file before upload it. To do this I use JSNI to read the file header using HTML5 filereader API. However my problem is that GWT does not wait for the result of the reading and continue the code execution. The side effect is that my boolean is not set yet and my condition goes wrong. Is there any mechanism like promise implemented in GWT?
Any help on this would be much appreciated!
UploadImageButtonWidget.java
private boolean isMimeTypeValid = false;
private String mimeType = null;
public native boolean isValid(Element element)/*-{
var widget = this;
var files = element.files;
var reader = new FileReader();
var CountdownLatch = function (limit){
this.limit = limit;
this.count = 0;
this.waitBlock = function (){};
};
CountdownLatch.prototype.countDown = function (){
this.count = this.count + 1;
if(this.limit <= this.count){
return this.waitBlock();
}
};
CountdownLatch.prototype.await = function(callback){
this.waitBlock = callback;
};
var barrier = new CountdownLatch(1);
reader.readAsArrayBuffer(files[0]);
reader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
widget.#com.portal.client.widgets.base.UploadImageButtonWidget::setMimeType(Ljava/lang/String;)(header);
barrier.countDown();
}
return barrier.await(function(){
return widget.#com.portal.client.widgets.base.UploadImageButtonWidget::isMimeTypeValid();
});
}-*/
public void setMimeType(String headerString) {
boolean mimeValid = true;
if (headerString.equalsIgnoreCase(PNG_HEADER)) {
mimeType = PNG_MIMETYPE;
} else if (headerString.equalsIgnoreCase(GIF_HEADER)) {
mimeType = GIF_MIMETYPE;
} else if (headerString.equalsIgnoreCase(JPG_HEADER1) || headerString.equalsIgnoreCase(JPG_HEADER2) || headerString.equalsIgnoreCase(JPG_HEADER3)) {
mimeType = JPG_MIMETYPE;
} else {
mimeValid = false;
setValidationError(i18n.uploadErrorNotImageBasedOnMimeType());
fileChooser.getElement().setPropertyJSO("files", null);
setErrorStatus();
}
setMimeTypeValid(mimeValid);
}
public boolean isMimeTypeValid() {
GWT.log("mimeType" + mimeType);
GWT.log("isMimetypeValid" + String.valueOf(isMimeTypeValid));
return mimeType != null;
}
in the activity:
public void validateAndUpload() {
UploadImageButtonWidget uploadImageButtonWidget = view.getUpload();
if (uploadImageButtonWidget.isValid()) {
GWT.log("mime ok: will be uploaded");
uploadImage();
} else {
GWT.log("mime not ok: will not be uploaded");
}
}

Nativescript custom control - Update Dependency Property

I'm creating a custom component which is a list of Buttons.
When the user clicks on a button, i change its css class and then i would like to add it in a custom "selectedItems" property to retrieve it in my ViewModel.
When I do a push on the "selectedItems" array property, no event is raised and I don't get the information.
Also, I tried to re-set the entire array but not better.
I don't know how to achieve this.
Here is the code of my component :
import {WrapLayout} from "ui/layouts/wrap-layout";
import {EventData} from "data/observable";
import {ValueButton} from "./value-button";
import dependencyObservableModule = require("ui/core/dependency-observable");
export class ValuesSelector extends WrapLayout {
public static itemsProperty = new dependencyObservableModule.Property(
"items",
"ValuesSelector",
new dependencyObservableModule.PropertyMetadata(
[],
dependencyObservableModule.PropertyMetadataSettings.None,
function(data: dependencyObservableModule.PropertyChangeData) {
if (data.newValue) {
let instance = <ValuesSelector>data.object;
instance.items = data.newValue;
}
}));
public static deleteOnClickProperty = new dependencyObservableModule.Property(
"deleteOnClick",
"ValuesSelector",
new dependencyObservableModule.PropertyMetadata(
false,
dependencyObservableModule.PropertyMetadataSettings.None));
public static selectedItemsProperty = new dependencyObservableModule.Property(
"selectedItems",
"ValuesSelector",
new dependencyObservableModule.PropertyMetadata(
[],
dependencyObservableModule.PropertyMetadataSettings.None));
public static singleSelectionProperty = new dependencyObservableModule.Property(
"singleSelection",
"ValuesSelector",
new dependencyObservableModule.PropertyMetadata(
false,
dependencyObservableModule.PropertyMetadataSettings.None));
public get selectedItems() {
return this._getValue(ValuesSelector.selectedItemsProperty);
}
public set selectedItems(value: any[]) {
this._setValue(ValuesSelector.selectedItemsProperty, value);
}
public get deleteOnClick() {
return this._getValue(ValuesSelector.deleteOnClickProperty);
}
public set deleteOnClick(value: boolean) {
this._setValue(ValuesSelector.deleteOnClickProperty, value);
}
public get singleSelection() {
return this._getValue(ValuesSelector.singleSelectionProperty);
}
public set singleSelection(value: boolean) {
this._setValue(ValuesSelector.singleSelectionProperty, value);
}
public get items() {
return this._getValue(ValuesSelector.itemsProperty);
}
public set items(value: any) {
this._setValue(ValuesSelector.itemsProperty, value);
this.createUI();
}
private _buttons: ValueButton[];
constructor() {
super();
this.orientation = "horizontal";
this._buttons = [];
}
private createUI() {
this.removeChildren();
let itemsLength = this.items.length;
for (let i = 0; i < itemsLength; i++) {
let itemButton = new ValueButton();
itemButton.text = this.items[i].label;
itemButton.value = this.items[i];
itemButton.className = "values-selector-item";
if (this.deleteOnClick) {
itemButton.className = "values-selector-selected-item";
}
itemButton.on(ValueButton.tapEvent, (data: EventData) => {
let clickedButton = <ValueButton>data.object;
if (this.deleteOnClick) {
let itemIndex = this.items.indexOf(clickedButton.value);
if (itemIndex > -1) {
let newSelectedItems = this.items;
newSelectedItems.splice(itemIndex, 1);
this.items = newSelectedItems;
}
return;
}
let internalSelectedItems = this.selectedItems;
if (clickedButton.className === "values-selector-item") {
if (this.singleSelection && this.selectedItems.length > 0) {
internalSelectedItems = [];
for (let i = 0; i < this._buttons.length; i++) {
this._buttons[i].className = "values-selector-item";
}
}
internalSelectedItems.push(clickedButton.value);
clickedButton.className = "values-selector-selected-item";
} else {
let itemIndex = internalSelectedItems.indexOf(clickedButton.value);
if (itemIndex > -1) {
internalSelectedItems.splice(itemIndex, 1);
}
clickedButton.className = "values-selector-item";
}
this.selectedItems = internalSelectedItems;
}, this);
this._buttons.push(itemButton);
this.addChild(itemButton);
}
}
}
Can you help me ?
Thanks
Ok I made a mistake by databinding my property.
In fact, in the XML I use the component like this :
<vs:ValuesSelector items="{{ criterias }}" selectedItems="{{ myObject.selectedCriterias }}" />
But in the ViewModel, I never initialized the selectedCriterias property because I thought that the default value [] specified in the component would create it.
So in the ViewModel, here is the fix :
Before
this.myObject = {
id : 0
};
After
this.myObject = {
id : 0,
selectedCriterias: []
};

Xamarin Forms - Resize Camera Picture

Someone helped me get this code for taking a picture using xamarin forms labs camera:
picker = DependencyService.Get<IMediaPicker> ();
task = picker.TakePhotoAsync (new CameraMediaStorageOptions {
DefaultCamera = CameraDevice.Rear,
MaxPixelDimension = 800,
});
img.BackgroundColor = Color.Gray;
Device.StartTimer (TimeSpan.FromMilliseconds (250), () => {
if (task != null) {
if (task.Status == TaskStatus.RanToCompletion) {
Device.BeginInvokeOnMainThread (async () => {
//img.Source = ImageSource.FromStream (() => task.Result.Source);
var fileAccess = Resolver.Resolve<IFileAccess> ();
string imageName = "img_user_" + User.CurrentUser().id + "_" + DateTime.Now.ToString ("yy_MM_dd_HH_mm_ss") + ".jpg";
fileName = imageName;
fileAccess.WriteStream (imageName, task.Result.Source);
fileLocation = fileAccess.FullPath(imageName);
FileStream fileStream = new FileStream(fileAccess.FullPath(imageName), FileMode.Open, System.IO.FileAccess.Read);
imageUrl = (string)test[0]["url"];
img.Source = imageUrl;
});
}
return task.Status != TaskStatus.Canceled
&& task.Status != TaskStatus.Faulted
&& task.Status != TaskStatus.RanToCompletion;
}
return true;
});
It saves the image, but the actual size of the phone picture taken is huge, is there a way to resize it.
UPDATE: The original answer is not useful, see below for updated answer. The issue was the PCL library was very slow and consumed too much memory.
ORIGINAL ANSWER (do not use):
I found an image I/O library, ImageTools-PCL, which I forked on github and trimmed down what wouldn't compile in Xamarin, keeping the modifications to minimum and the result seems to work.
To use it download the linked repository, compile it with Xamarin and add the DLLs from Build folder to your Forms project.
To resize an image you can do this (should fit the context of your question)
var decoder = new ImageTools.IO.Jpeg.JpegDecoder ();
ImageTools.ExtendedImage inImage = new ImageTools.ExtendedImage ();
decoder.Decode (inImage, task.Result.Source);
var outImage = ImageTools.ExtendedImage.Resize (inImage, 1024, new ImageTools.Filtering.BilinearResizer ());
var encoder = new ImageTools.IO.Jpeg.JpegEncoder ();
encoder.Encode (outImage, fileAccess.CreateStream (imageName));
ImageSource imgSource = ImageSource.FromFile (fileAccess.FullPath (imageName));
UPDATED ANSWER:
Get Xamarin.XLabs from nuget, learn about using Resolver, create an IImageService interface with Resize method.
Implementation for iOS:
public class ImageServiceIOS: IImageService{
public void ResizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight)
{
if (File.Exists(sourceFile) && !File.Exists(targetFile))
{
using (UIImage sourceImage = UIImage.FromFile(sourceFile))
{
var sourceSize = sourceImage.Size;
var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
if (!Directory.Exists(Path.GetDirectoryName(targetFile)))
Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
if (maxResizeFactor > 0.9)
{
File.Copy(sourceFile, targetFile);
}
else
{
var width = maxResizeFactor * sourceSize.Width;
var height = maxResizeFactor * sourceSize.Height;
UIGraphics.BeginImageContextWithOptions(new CGSize((float)width, (float)height), true, 1.0f);
// UIGraphics.GetCurrentContext().RotateCTM(90 / Math.PI);
sourceImage.Draw(new CGRect(0, 0, (float)width, (float)height));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
if (targetFile.ToLower().EndsWith("png"))
resultImage.AsPNG().Save(targetFile, true);
else
resultImage.AsJPEG().Save(targetFile, true);
}
}
}
}
}
Implementation of the service for Android:
public class ImageServiceDroid: IImageService{
public void ResizeImage(string sourceFile, string targetFile, float maxWidth, float maxHeight)
{
if (!File.Exists(targetFile) && File.Exists(sourceFile))
{
// First decode with inJustDecodeBounds=true to check dimensions
var options = new BitmapFactory.Options()
{
InJustDecodeBounds = false,
InPurgeable = true,
};
using (var image = BitmapFactory.DecodeFile(sourceFile, options))
{
if (image != null)
{
var sourceSize = new Size((int)image.GetBitmapInfo().Height, (int)image.GetBitmapInfo().Width);
var maxResizeFactor = Math.Min(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
string targetDir = System.IO.Path.GetDirectoryName(targetFile);
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
if (maxResizeFactor > 0.9)
{
File.Copy(sourceFile, targetFile);
}
else
{
var width = (int)(maxResizeFactor * sourceSize.Width);
var height = (int)(maxResizeFactor * sourceSize.Height);
using (var bitmapScaled = Bitmap.CreateScaledBitmap(image, height, width, true))
{
using (Stream outStream = File.Create(targetFile))
{
if (targetFile.ToLower().EndsWith("png"))
bitmapScaled.Compress(Bitmap.CompressFormat.Png, 100, outStream);
else
bitmapScaled.Compress(Bitmap.CompressFormat.Jpeg, 95, outStream);
}
bitmapScaled.Recycle();
}
}
image.Recycle();
}
else
Log.E("Image scaling failed: " + sourceFile);
}
}
}
}
#Sten's answer might encounter out-of-memory problem on some android devices. Here's my solution to implement the ResizeImage function
, which is according to google's "Loading Large Bitmaps Efficiently" document:
public void ResizeImage (string sourceFile, string targetFile, int reqWidth, int reqHeight)
{
if (!File.Exists (targetFile) && File.Exists (sourceFile)) {
var downImg = decodeSampledBitmapFromFile (sourceFile, reqWidth, reqHeight);
using (var outStream = File.Create (targetFile)) {
if (targetFile.ToLower ().EndsWith ("png"))
downImg.Compress (Bitmap.CompressFormat.Png, 100, outStream);
else
downImg.Compress (Bitmap.CompressFormat.Jpeg, 95, outStream);
}
downImg.Recycle();
}
}
public static Bitmap decodeSampledBitmapFromFile (string path, int reqWidth, int reqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
var options = new BitmapFactory.Options ();
options.InJustDecodeBounds = true;
BitmapFactory.DecodeFile (path, options);
// Calculate inSampleSize
options.InSampleSize = calculateInSampleSize (options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.InJustDecodeBounds = false;
return BitmapFactory.DecodeFile (path, options);
}
public static int calculateInSampleSize (BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
int height = options.OutHeight;
int width = options.OutWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
int halfHeight = height / 2;
int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
You can do this natively for each platform and use an interface. Heres an example for IOS
In your PCL project you need to add an interface
public interface IImageResizer
{
byte[] ResizeImage (byte[] imageData, double width, double height);
}
Then to resize an image in your code, you can load the IOS implementation of that interface using the DependencyService and run the ResizeImage method
var resizer = DependencyService.Get<IImageResizer>();
var resizedBytes = resizer.ResizeImage (originalImageByteArray, 400, 400);
Stream stream = new MemoryStream(resizedBytes);
image.Source = ImageSource.FromStream(stream);
IOS Implementation, add this class to your IOS project.
[assembly: Xamarin.Forms.Dependency (typeof (ImageResizer_iOS))]
namespace YourNamespace
{
public class ImageResizer_iOS : IImageResizer
{
public byte[] ResizeImage (byte[] imageData, double maxWidth, double maxHeight)
{
UIImage originalImage = ImageFromByteArray (imageData);
double width = 300, height = 300;
double maxAspect = (double)maxWidth / (double)maxHeight;
double aspect = (double)originalImage.Size.Width/(double)originalImage.Size.Height;
if (maxAspect > aspect && originalImage.Size.Width > maxWidth) {
//Width is the bigger dimension relative to max bounds
width = maxWidth;
height = maxWidth / aspect;
}else if (maxAspect <= aspect && originalImage.Size.Height > maxHeight){
//Height is the bigger dimension
height = maxHeight;
width = maxHeight * aspect;
}
return originalImage.Scale(new SizeF((float)width,(float)height)).AsJPEG ().ToArray ();
}
public static MonoTouch.UIKit.UIImage ImageFromByteArray(byte[] data)
{
if (data == null) {
return null;
}
MonoTouch.UIKit.UIImage image;
try {
image = new MonoTouch.UIKit.UIImage(MonoTouch.Foundation.NSData.FromArray(data));
} catch (Exception e) {
Console.WriteLine ("Image load failed: " + e.Message);
return null;
}
return image;
}
}
}
An update from the Xamarin Media Plugin allows you to resize the image
https://github.com/jamesmontemagno/MediaPlugin
... barring that, and you need a more generic resize option (say the image comes from a web call, and not the device, then have a look at:
https://github.com/InquisitorJax/Wibci.Xamarin.Images

How to show PopUp with in the screen area In Flex and AS3

Hi i am trying to show my popup on the image mouse over
it is showing fine
when i trying mouse over right side last images popup is going out of the screen
Here TalentInfoPopUp is **TitleWindow
This is my sample code
private static var staticWindow :TalentInfoPopUp = null;
private static var visibleWindow:TalentInfoPopUp = null;
public static function show(t:Object, parent : DisplayObject, x:Number , y:Number):void
{
if(staticWindow == null)
{
visibleWindow = staticWindow = PopUpManager.createPopUp( parent , TalentInfoPopUp , false) as TalentInfoPopUp;
}
else if(visibleWindow == null)
{
visibleWindow = staticWindow;
PopUpManager.addPopUp(staticWindow, parent, false);
}
PopUpManager.centerPopUp(staticWindow);
staticWindow.talent = t;
staticWindow.x = x;
staticWindow.y =y;
PopUpManager.bringToFront(staticWindow);
staticWindow.talent = t;
staticWindow.move(x,y);
staticWindow.callLater(staticWindow.setPosition,[x,y]);
//staticWindow.setPosition(x,y);
}
private function setPosition(nx:int,ny:int):void
{
var maxWidth:int = stage.width ;
var maxHeight:int = stage.height;
if(nx>maxWidth-width)
{
nx=nx-width;
}
if(ny>maxHeight-height)
{
ny=ny-height;
}
this.move(nx,ny);
}
Try using systemManager.screen.width and systemManager.screen.height instead of stage.width and stage.height; also learn about the localToGlobal and globalToLocal methods and how to use them.

as3: reloading an image

I have an image that I am attempting to load, and then reload. Here is my code for the loading of the image:
public function loadImage(url:String, _w:int, _h:int):void
{
this._stwidth = _w;
this._stheight = _h;
this._imageURL = url;
if(!_imageURL)
{
return;
}
this.alpha = 1.0; //need this because we might have just faded the image out
_ldr.alpha = 0.0;
_prog.alpha = 1.0;
_sqr.alpha = 0.0;
_sqr.graphics.clear();
if(_hasLoaded)
{
try
{
_ldr.close();
_ldr.unload();
}
catch(e:Error)
{
//trace("bmdisplay has loaded once, but there was an error: " + e.message);
}
}
_ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(Event.INIT, onOpen);
_ldr.load(new URLRequest(_imageURL));
}
For some reason, this code will not load the image without issuing an Error upon the 2nd load.
Can someone please help me figure this out?
I am totally lost on why my variable _asLoaded would do me wrong.
I have an onComplete() handler, which sets that var to true, and I never set it to false after that.
I don't know what else I should be trying...
Thanks
Sometimes back I wrote a helper class to achieve something similar. The helper class extends Loader and provides automatic scaling of image. Here is the code for that class:package {
import flash.display.Loader;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
public class ImageLoader extends Loader {
private var _imageURL:String; // URL of image
private var _imageBoundary:Rectangle; // boundary rectangle for the image
private var _loaded:Boolean; // flag which tells whether image is loaded or not.
private var _isLoading:Boolean; // flag which say if any loading is in progress
//Constructor function, which calls Loader's constructor
// and loads and resize the image
public function ImageLoader(url:String = null, rect:Rectangle = null):void {
super();
_imageURL = url;
_imageBoundary = rect;
_loaded = false;
_isLoading = false;
loadImage();
}
// sets the image for the loader and loads it
public function set imageURL(url:String):void {
_imageURL = url;
loadImage();
}
// sets the boundary of the image and resizes it
public function set boundary(rect:Rectangle):void {
_imageBoundary = rect;
resizeImage();
}
private function removeListeners():void {
this.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
this.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onError);
this.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function onComplete(e:Event):void {
_loaded = true;
_isLoading = false;
removeListeners();
resizeImage();
}
//In case of error, we are not propogating the event
private function onError(e:Event):void {
e.stopImmediatePropagation();
removeListeners();
}
// real loading goes here
// it first closes and unloads the loader and
// then loads the image
private function loadImage():void {
if (_isLoading) {
trace("Some loading is in progess");
return;
}
try {
this.close();
this.unload();
}
catch(e:Error) {
//discarded
}
if (!_imageURL)
return;
_loaded = false;
_isLoading = true;
this.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
this.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
this.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
this.load(new URLRequest(_imageURL));
}
// standard resizing function for image so that it's
// aspect ratio is maintained.
private function resizeImage():void {
if (!_imageBoundary || !_loaded)
return;
var aspect:Number = width / height;
var cAspect:Number = _imageBoundary.width / _imageBoundary.height;
if (aspect <= cAspect) {
this.height = _imageBoundary.height;
this.width = aspect * this.height;
}
else {
this.width = _imageBoundary.width;
this.height = this.width / aspect;
}
this.x = (_imageBoundary.width-this.width)/2 + _imageBoundary.x;
this.y = (_imageBoundary.height-this.height)/2 + _imageBoundary.y;
}
}
} And you can use it like this:var _imageLoader:ImageLoader = new ImageLoader();
_imageLoader.imageURL = "http://some-image-url";
_imageLoader.boundary = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); // or whatever suits you
ImageLoader extends Loader class so you can listen to all the Events dispatches by Loader class. Hope it helps.
i would declare _ldr inside the function so its dead every time you start this function. and i also would not use this unload() and close() methods. its much simpler if make some thing like this (you need to have a empty movieclip called "ldrHelper"):
public function loadImage(url:String, _w:int, _h:int):void
{
// do your job and die bravely, no need to be global
var _ldr:Loader = new Loader();
this._stwidth = _w;
this._stheight = _h;
this._imageURL = url;
if(!_imageURL)
{
return;
}
this.alpha = 1.0; //need this because we might have just faded the image out
// now you will need to make alpha = 1 on ldrHolder since _ldr is dead after this function
ldrHolder.alpha = 0.0;
_prog.alpha = 1.0;
_sqr.alpha = 0.0;
_sqr.graphics.clear();
// remove the old image, doesn't matter whether its empty or not
while(ldrHolder.numChildren > 0){
ldrHolder.removeChildAt(0);
}
//add image
ldrHolder.addChild(_ldr);
_ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
_ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
_ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_ldr.contentLoaderInfo.addEventListener(Event.INIT, onOpen);
_ldr.load(new URLRequest(_imageURL));
}
Try instantiating new Loader, probably trying to recycle it is giving you the problem

Resources