cocos2d-html5 get sprite from cache plist - cocos2d-html5

I am using cocos2d-js v3.0 with html5 and I am loading a plist into cache and them I am trying to create a sprite from.
I am getting the error
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (player-stand-f-0, line 0)
As far as I am aware .createWithSpriteFrameName is deprecated but all examples show to use this.
The code:
var cache = cc.spriteFrameCache;
cache.addSpriteFrames(player.plist, player.png);
this.sprite = cc.Sprite.createWithSpriteFrameName("player-stand-f-0");
this.sprite.setPosition(new cc.Point(300,300));
this.addChild(this.sprite);
player.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>frames</key>
<dict>
<key>player-sit-f-0</key>
<dict>
<key>frame</key>
<string>{{3,108},{77,95}}</string>
<key>offset</key>
<string>{0,0}</string>
<key>rotated</key>
<false/>
<key>sourceColorRect</key>
<string>{{0,0},{77,95}}</string>
<key>sourceSize</key>
<string>{77,95}</string>
</dict>

I used
this.sprite = new cc.Sprite("#player-stand-f-0");
instead of
this.sprite = cc.Sprite.createWithSpriteFrameName("player-stand-f-0");

// create sprite sheet
cc.SpriteFrameCache.getInstance().addSpriteFrames(spritesheet_plist); // add Spritesheet Plist
var SpriteSheet = cc.SpriteBatchNode.create(spritesheet_png); // add Spritesheet Png
this.addChild(SpriteSheet,1);
// Push the frames for animation
var animFrames = [];
for (var i = 0; i < 6; i++) {
var str = "sequence_" + i + ".png";
var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(str);
animFrames.push(frame);
}
// taadaa ...!! Animate the sprites
var animation = cc.Animation.create(animFrames, 0.06);
var sprite = cc.Sprite.createWithSpriteFrameName("sequence_0.png");
sprite.setAnchorPoint(0.5,0.5); // optional
sprite.setScale(1.0,1.0); // optional
sprite.setPosition(widhthPostion, heightPosition);
sprite.runAction(cc.RepeatForever.create(cc.Animate.create(animation)));
SpriteSheet.addChild(sprite,1);

Related

xamarin iOS ONLY Plugin.Geolocator Authorization Error

Hi I have some code that gets the geolocationposition it works in andproid but not in iOS.
In iOS only using the Plugin.Geolocator I get
Location permission denied, can not get positions async. Unhandled
Exception: Plugin.Geolocator.Abstractions.GeolocationException: A
geolocation error occured: Unauthorized
below is what I have in the plist (removed not relevant stuff)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
etc.......
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to location when open and in the background.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Can we use your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We are using your location</string>
<key>RequestWhenInUseAuthorization</key>
<string>Need location for geolocator plugin</string>
</dict>
</plist>
It's working for android so I guess cannot be code but settings.
any suggestions?
EDIT
Tried the sample that comes with the plugin itself and even though seems to work
i see an error in the output window. Do I need to set some settings in the emulator ? how?
GeolocatorSampleiOS[16172:675663091] Location permission denied, can
not get positions async.
code I use for both android and iOS (works with android)
private async Task<Location> GetDeviceLocationAsync2()
{
try
{
var locator = CrossGeolocator.Current;
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
if (results.ContainsKey(Permission.Location))
{
status = results[Permission.Location];
}
}
var currentLocation = await Xamarin.Essentials.Geolocation.GetLastKnownLocationAsync();
if (currentLocation != null)
{
return currentLocation;
}
if (!locator.IsGeolocationAvailable || !locator.IsGeolocationEnabled)
{
//todo
return null;
}
if (status == PermissionStatus.Granted)
{
var request = new GeolocationRequest(
GeolocationAccuracy.Best,
new TimeSpan(30000))
{
DesiredAccuracy = GeolocationAccuracy.Best
};
currentLocation =await Xamarin.Essentials.Geolocation.GetLocationAsync(request);
LogCurrentLocation(currentLocation);
}
else if (status != PermissionStatus.Unknown)
{
await DisplayDialogAsync("Location denied", "Do not have access to location");
}
return currentLocation;
}
catch (FeatureNotSupportedException ex)
{
// Handle not supported on device exception
//todo:add logging
}
catch (PermissionException ex)
{
// Handle permission exception
//todo:add logging
}
catch (Exception ex)
{
// Unable to get location
//todo:add logging
}
return null;
}
Solved.
I needed to set permissions in the emulator!!!

Xamarin forms (android project) error rendering image using Skia graphics library

I am trying to load and render an image using the skia graphics library in my xamarin forms solution. When I try to render the image (running the android project) I get the following error:
Value cannot be null. Parameter name: codec
here is the code:
void OnPainting(object sender, SKPaintSurfaceEventArgs e)
{
var surface = e.Surface;
var canvas = surface.Canvas;
canvas.Clear(SKColors.White);
var filename = "test.jpg";
using (var stream = new SKFileStream(filename))
using (var bitmap = SKBitmap.Decode(stream)) // the error occurs on this line
using (var paint = new SKPaint())
{
canvas.DrawBitmap(bitmap, SKRect.Create(200, 200), paint);
}
}
I cannot find any sample code online for xamarin. Any sample code or links would be much appreciated.
thanks in advance
Value cannot be null. Parameter name: codec
I think it is possible you get a null object here: using (var stream = new SKFileStream(filename)). I tried to created a demo, and it works fine.
XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:skiaviews="clr-namespace:SkiaSharp.Views.Forms;assembly=SkiaSharp.Views.Forms"
x:Class="FormsIssue6.Page1">
<Grid>
<skiaviews:SKCanvasView x:Name="mycanvas" PaintSurface="OnPainting" />
</Grid>
</ContentPage>
Code behind:
private void OnPainting(object sender, SkiaSharp.Views.Forms.SKPaintSurfaceEventArgs e)
{
var surface = e.Surface;
var canvas = surface.Canvas;
var assembly = typeof(Page1).GetTypeInfo().Assembly;
var fileStream = assembly.GetManifestResourceStream("YOUR-FILE-FULL-NAME");
// clear the canvas / fill with white
canvas.DrawColor(SKColors.White);
// decode the bitmap from the stream
using (var stream = new SKManagedStream(fileStream))
using (var bitmap = SKBitmap.Decode(stream))
using (var paint = new SKPaint())
{
// create the image filter
using (var filter = SKImageFilter.CreateBlur(5, 5))
{
paint.ImageFilter = filter;
// draw the bitmap through the filter
canvas.DrawBitmap(bitmap, SKRect.Create(640, 480), paint);
}
}
}
The file name in the code above should be like "YOUR PROJECT NAMESPACE"."File NAME", and this file is placed in PCL and build action of this file must be "Embedded Resource". For more information about working with file, you can refer to Files.
I cannot find any sample code online for xamarin. Any sample code or links would be much appreciated.
The package itself on Github has a code sample for Xamarin.Forms, you can refer to FormsSample.

Xamarin forms - set switch text color

How can I set the color of the text in an android renderer? I have the following renderer:
public class CustomSwitchRenderer : SwitchRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Switch> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.TextOn = "Yes";
Control.TextOff = "No";
Android.Graphics.Color colorOn = Android.Graphics.Color.Rgb(239, 201, 6);
Android.Graphics.Color colorOff = Android.Graphics.Color.LightGray;
Android.Graphics.Color colorDisabled = Android.Graphics.Color.Gray;
Android.Graphics.Color textColor = Android.Graphics.Color.Black;
Control.SetTextColor (ColorStateList.ValueOf (textColor));
Control.SetTextColor (textColor);
StateListDrawable drawable = new StateListDrawable();
drawable.AddState(new int[] { Android.Resource.Attribute.StateChecked }, new ColorDrawable(colorOn));
drawable.AddState(new int[] { -Android.Resource.Attribute.StateEnabled }, new ColorDrawable(colorDisabled));
drawable.AddState(new int[] { }, new ColorDrawable(colorOff));
Control.ThumbDrawable = drawable;
}
}
}
I am able to change the color of the switch, but I can't figure out how to change the color of the YES/NO text. SetTextColor doesn't seem to work.
Create an xml file under the Resources\values directory in your droid project.
doesn't matter the name but it needs to end in .xml and contain
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="#android:style/TextAppearance.Medium">
<item name="android:textColor">#00FF00</item>
</style>
</resources>
Then in your renderer call Control.SetSwitchTextAppearance. Pass in the Context and the ResId of the resource you created. You can get the Id from the generated file under Resources titled Resource.designer.cs. Alternately you can call the Const that generated as follows.
Control.SetSwitchTextAppearance (Control.Context, Resource.Style.CodeFont);
Hope it helps. If you cant get it let me know Ill upload a sample app.

I need to remove an image from the stage when I drop it onto the trash can image in AS3

I need to remove the image from the stage whenever I drag and drop "into" the trash can. I have been looking at this forever and really cant seem to find a solution.
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Image;
//array of movies
public var myArray:Array = ["batman.jpg","cabin.jpg","christmasVacation.jpg"];
//init function
public function init():void{
var trashImage:Image = new Image();
//set trash img
trashImage.source = "asset/trash.jpg";
//adds img to stage
trashGrp.addElement(trashImage);
//loops 4 times
for(var i:Number = 0; i < myArray.length; i++){
var arrayEntry:String = myArray[i];
//makes new image
var newImage:Image = new Image();
//sets the image source for each image
newImage.source = "asset/" + arrayEntry;
//adds the image to the stage
grpMovies.addElement(newImage);
//set drag/drop
newImage.addEventListener(MouseEvent.MOUSE_DOWN, dragMe);
newImage.addEventListener(MouseEvent.MOUSE_UP, dropMe);
}
}
//dragMe function
public function dragMe(e:MouseEvent):void
{
// Get the Image that saw the mouse-down.
var img:Image = Image(e.currentTarget);
// Use the built-in method to start dragging.
img.startDrag();
}
//dropMe function
public function dropMe(e:MouseEvent):void
{
// Get the Image that saw the mouse-up.
var img:Image = Image(e.currentTarget);
// Use the built-in method to stop dragging.
img.stopDrag();
-**this is where my issue is. I cant get it to remove it when the image is hit**
if (trashGrp.hitTestObject(img)) {
grpMovies.removeElement(img);
}
}
]]>
</fx:Script>
<s:TileGroup id="grpMovies" columnWidth="225" rowHeight="225" requestedRowCount="1"
paddingTop="20"/>
<s:HGroup id= "trashGrp" x="950" y="20"/>
</s:Application>
Check out the following code, I think it does what you want. I modified the event handler to be attached to the main container, so that it gets triggered properly when you release the mouse button on the trash can.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="init()">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Image;
//array of movies
public var myArray:Array = ["batman.jpg","cabin.jpg","christmasVacation.jpg"];
private var _draggedImage:Image;
//init function
public function init():void{
var trashImage:Image = new Image();
//set trash img
trashImage.source = "assets/trash.png";
trashImage.mouseEnabled = false;
trashImage.mouseChildren = false;
//adds img to stage
trashGrp.addElement(trashImage);
//loops 4 times
for(var i:Number = 0; i < myArray.length; i++){
var arrayEntry:String = myArray[i];
//makes new image
var newImage:Image = new Image();
//sets the image source for each image
newImage.source = "assets/"+arrayEntry;
//adds the image to the stage
grpMovies.addElement(newImage);
//set drag/drop
newImage.addEventListener(MouseEvent.MOUSE_DOWN, dragMe);
}
}
//dragMe function
public function dragMe(e:MouseEvent):void
{
// Get the Image that saw the mouse-down.
var img:Image = Image(e.currentTarget);
// Use the built-in method to start dragging.
img.startDrag();
_draggedImage = img;
this.addEventListener(MouseEvent.MOUSE_UP, dropMe);
}
//dropMe function
public function dropMe(e:MouseEvent):void
{
_draggedImage.stopDrag();
this.removeEventListener(MouseEvent.MOUSE_UP, dropMe);
if (trashGrp.hitTestObject(_draggedImage)) {
grpMovies.removeElement(_draggedImage);
_draggedImage = null;
}
}
]]>
</fx:Script>
<s:TileGroup id="grpMovies" columnWidth="225" rowHeight="225" requestedRowCount="1"
paddingTop="20"/>
<s:HGroup id= "trashGrp" x="950" y="20"/>
</s:Application>

nsIUploadChannel - The connection was reset

I try to save post data to local file. But if i do that, in browser i see
The connection was reset
The connection to the server was reset while the page was
loading. The site could be temporarily unavailable or too busy. Try
again in a few
moments. If you are unable to load any pages, check your
computer's network
connection. If your computer or network is protected by a
firewall or proxy, make sure
that Firefox is permitted to access the Web.
There is my code:
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="yourwindow" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script>
<![CDATA[
var MIKI =
{
observe: function(subject, topic, data)
{
if (topic == "http-on-modify-request")
{
var httpChannel = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
if(httpChannel.requestMethod == "POST"){
var uploadChannel = httpChannel.QueryInterface(Components.interfaces.nsIUploadChannel);
var uploadChannelStream = uploadChannel.uploadStream;
uploadChannelStream.QueryInterface(Components.interfaces.nsISeekableStream);
uploadChannelStream.seek(0,0);
var stream = Components.classes['#mozilla.org/scriptableinputstream;1'].createInstance(Components.interfaces.nsIScriptableInputStream);
stream.init(uploadChannelStream);
var data = stream.read(stream.available());
data = data.split(/\r\n\r\n/).slice(1).join('\r\n\r\n');
var buffer = httpChannel.URI.spec + " " + data+ "\n";
if(data != '') fos.write(buffer, buffer.length);
}
}
}
};
var file = Components.classes["#mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("Desk", Components.interfaces.nsIFile);
file.append("http-request-log.txt");
var fos = Components.classes["#mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
fos.init(file, 0x02 | 0x08 | 0x10, -1, 0);
var observerService = Components.classes["#mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
observerService.addObserver(MIKI, "http-on-modify-request", false);
]]>
</script>
</window>
What i do wrong?
Since you are reading the data out of the upload stream to write it to the file, you are probably leaving the stream pointer at the end (so when the request happens it looks like the POST body is empty). Try seeking back to the beginning of the stream once you are done reading out the data.

Resources