How can I use Writablebitmap in ScheduledTask in windows phone 8? - windows-phone-8

I want to update my live tile by creating and saving a writable bitmap image in scheduled task agent.my code works inside the app but in background task, it breaks into the debugger
I'm using this simple code:
protected override void OnInvoke(ScheduledTask task)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
#endif
CreateWideTile();
NotifyComplete();
}
and my code to create and save image is this:
private void CreateWideTile()
{
int width = 691;
int height = 336;
string imagename = "WideBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var background = new Canvas();
background.Height = b.PixelHeight;
background.Width = b.PixelWidth;
//Created background color as Accent color
SolidColorBrush backColor = new SolidColorBrush(Colors.Red);
background.Background = backColor;
var textBlock = new TextBlock();
textBlock.Text = "Example text";
textBlock.FontWeight = FontWeights.Normal;
textBlock.TextAlignment = TextAlignment.Left;
textBlock.Margin = new Thickness(20, 20, 0, 0);
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Foreground = new SolidColorBrush(Colors.White); //color of the text on the Tile
textBlock.FontSize = 30;
canvas.Children.Add(textBlock);
b.Render(background, null);
b.Render(canvas, null);
b.Invalidate(); //Draw bitmap
//Save bitmap as jpeg file in Isolated Storage
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/" + imagename + ".jpg", System.IO.FileMode.Create, isf))
{
b.SaveJpeg(imageStream, b.PixelWidth, b.PixelHeight, 0, 100);
}
}
}
when I test the app, after executing background task, an error comes that point to Debugger.Break();
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
I don't understand the reason. my code works in foreground app but not in background ...
any solution ????

You should use dispatcher, because WriteableBitmap.Render should be used in the UI thread:
protected override void OnInvoke(ScheduledTask task)
{
Deployment.Current.Dispatcher.BeginInvoke( () =>
{
CreateWideTile();
NotifyComplete();
} );
}

Related

GeoTools - drawing points on image

I'm using geoTools 14.1
I'm trying to plot on an image some points
This is the code I'm using:
double[][] points = new double[8][2];
points[0] = new double[]{45.46433710338643, 9.190417528152478};
points[1] = new double[]{45.46195085146914, 9.189746320685355};
points[2] = new double[]{45.460062304163635, 9.19015527826191};
points[3] = new double[]{45.472950871127445, 9.17363731952788};
points[4] = new double[]{45.4737153001908,9.203728795018847};
points[5] = new double[]{45.4849795331724,9.20162835217198};
points[6] = new double[]{45.48560542313713,9.195953607559215};
points[7] = new double[]{45.48348421787171,9.188765287399292};
final SimpleFeatureType TYPE = DataUtilities.createType("Location",
"location:Point:srid=3857,"+// <- the geometry attribute: Point type
"nome:String," + // <- a String attribute
"id:Integer" // a number attribute
);
FeatureCollection<SimpleFeatureType, SimpleFeature> collection = new DefaultFeatureCollection();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
CoordinateReferenceSystem pointSrc = CRS.decode("EPSG:4326");
CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:3857");
MathTransform transform = CRS.findMathTransform(pointSrc, targetCRS);
for (int i = 0; i < points.length; i++)
{
double[] coords = points[i];
Point point = geometryFactory.createPoint(new Coordinate(coords[0], coords[1]));
Point converted = (Point) JTS.transform( point, transform);
featureBuilder.add(converted);
featureBuilder.add("Punto "+i);
featureBuilder.add(i);
SimpleFeature feature = featureBuilder.buildFeature(""+i);
logger.info(""+feature+" feature.getDefaultGeometry() "+feature.getDefaultGeometry()+ " feature.getDefaultGeometryProperty() "+feature.getDefaultGeometryProperty());
((DefaultFeatureCollection)collection).add(feature);
}
String wellKnownName = "Circle";
Style style = SLD.createPointStyle(wellKnownName,Color.RED,Color.RED,0f,10f);
FeatureLayer fl = new FeatureLayer(collection, style);
fl.setVisible(true);
fl.setSelected(true);
logger.info(""+fl);
mapcontent.addLayer((org.geotools.map.Layer)fl); //"1010177.1917802,5688070.7096562,1029133.5747922,5704122.4855938"
ReferencedEnvelope bounds = new ReferencedEnvelope(1010177.1917802,1029133.5747922,5688070.7096562, 5704122.4855938, targetCRS);
BufferedImage ret = buildImage(mapcontent, 5000, 5000, bounds, Color.white);
ImageIO.write((RenderedImage) ret, "png", new File("/home/angelo/Scrivania/immagineResult.png"));
It seems to me all correct, but the generated image contains no point.
This is the generated image
As you can see it's all white; I was expecting only 8 red circles on the image... Is there any error in my code? Am I doing anything wrong?
Thank you
Angelo
UPDATE: added build image method
public BufferedImage buildImage(final MapContent map, final int imageWidth,final int imageHeight,ReferencedEnvelope bounds,Color bgcolor) {
GTRenderer renderer = new StreamingRenderer();
renderer.setMapContent(map);
renderer.setMapContent(map);
Rectangle imageBounds = null;
ReferencedEnvelope mapBounds = bounds;
try {
if(bounds==null) mapBounds = map.getMaxBounds();
imageBounds = new Rectangle(imageWidth, imageHeight);
} catch (Exception e) {
failed to access map layers
throw new RuntimeException(e);
}
BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D gr = image.createGraphics();
int type = AlphaComposite.SRC;
gr.setComposite(AlphaComposite.getInstance(type));
Color c = new Color(bgcolor.getRed(), bgcolor.getGreen(), bgcolor.getBlue(), 0);
gr.setBackground(bgcolor);
gr.setColor(c);
gr.fillRect(0, 0, image.getWidth(), image.getHeight());
type = AlphaComposite.SRC_OVER;
gr.setComposite(AlphaComposite.getInstance(type));
try {
renderer.paint(gr, imageBounds, bounds);
} catch (Exception e) {
throw new RuntimeException(e);
}
return image;
}
After a lot of playing I have found the problem :-) There is no bug in your code! There are in fact 8 red dots in that white image, but they are very hard to find!
As the above image shows at 2000% zoom (and panning along the top edge) you will find a dot (I'm assuming the others are there) - the simple answer is either to make the dots 10 times bigger (100px) or the image much smaller (500x500) and in both cases the dots are immediately visible.

Using the Feathers ScreenNavigator with Starling and Signals

I'm new to Flash, Starling, and Feathers and am giving myself a kind of crash course, but am getting confused. I simply want my root starling class to initiate my game screen. I apologize if this is noobish. I really do want to understand.
I am not sure what dispatches FeathersEventType.INITIALIZE and I'm having trouble dispatching it manually. Any pointers in the right direction would be greatly appreciated.
In my Main.as (my Document Class), I instantiate starling, wait for the Root to be created, and then call its Start function (saw this in an example of how to show an initial background, not sure if it's best practice).
this.mStarling = new Starling(Root, this.stage, viewPort);
... //set background from embed
mStarling.addEventListener(starling.events.Event.ROOT_CREATED,
function(event:Object, app:Root):void
{
mStarling.removeEventListener(starling.events.Event.ROOT_CREATED, arguments.callee);
removeChild(background);
background = null;
var bgTexture:Texture = Texture.fromEmbeddedAsset(
backgroundClass, false, false);
//app.start(bgTexture, assets);
app.start(bgTexture, assets) // call the START on my root class
mStarling.start();
});
Here's my Root class (which is the root class passed to Starling)
public function Root()
{
if (verbose) trace(this + "Root(" + arguments);
super();
this.addEventListener(FeathersEventType.INITIALIZE, initializeHandler);
}
// this is not being called
private function initializeHandler(e:Event):void
{
this._navigator.addScreen(GAME_SCREEN, new ScreenNavigatorItem(GameScreen,
{
complete: MAIN_MENU
}));
}
public function start(background:Texture, assets:AssetManager):void
{
sAssets = assets; // assets loaded on document class
addChild(new Image(background)); // passed from doc class
this._navigator = new ScreenNavigator();
this.addChild(this._navigator);
var progressBar:ProgressBar = new ProgressBar(300, 20);
progressBar.x = (background.width - progressBar.width) / 2;
progressBar.y = (background.height - progressBar.height) / 2;
progressBar.y = background.height * 0.85;
addChild(progressBar);
// Progress bar while assets load
assets.loadQueue(function onProgress(ratio:Number):void
{
progressBar.ratio = ratio;
if (ratio == 1)
Starling.juggler.delayCall(function():void
{
gameScreen = new GameScreen();
trace("got this far" + gameScreen);
gameScreen.GAME_OVER.add(gotoGameOverScreen);
gameOverScreen = new GameOverScreen();
gameOverScreen.PLAY_AGAIN.add(gotoGameScreen);
progressBar.removeFromParent(true);
// This is where I'd like the GAME_SCREEN to show.
// now would be a good time for a clean-up
System.pauseForGCIfCollectionImminent(0);
System.gc();
}, 0.15);
});
This is part of my Root Class
public function start(background:Texture, assets:AssetManager):void
{
stageW= int(stage.stageWidth);
stageH = int(stage.stageHeight);
sAssets = assets;
bgIma=new Image(background);
bgIma.height=g.stageH * 0.4;
bgIma.scaleX=bgIma.scaleY;
bgIma.x=(g.stageW-bgIma.width)>>1;
bgIma.y=(g.stageH-bgIma.height)>>1;
addChild(bgIma);
var progressBar:ProgressBar = new ProgressBar(175, 20);
progressBar.x = (g.stageW - progressBar.width) >> 1;
progressBar.y = (g.stageH - progressBar.height) >> 1;
progressBar.y = g.stageH * 0.8;
addChild(progressBar);
assets.loadQueue(function onProgress(ratio:Number):void
{
progressBar.ratio = ratio;
if (ratio == 1)
Starling.juggler.delayCall(function():void
{
progressBar.removeFromParent(true);
removeChild(bgIma);
bgIma=null;
addedToStageHandler();
addSounds();
System.pauseForGCIfCollectionImminent(0);
System.gc();
}, 0.15);
});
}
protected function addedToStageHandler(event:starling.events.Event=null):void
{
this._navigator = new ScreenNavigator();
_navigator.autoSizeMode = ScreenNavigator.AUTO_SIZE_MODE_CONTENT;
this.addChild( this._navigator );
this._transitionManager = new ScreenFadeTransitionManager(_navigator);
this._navigator.addScreen( "Fluocode", new ScreenNavigatorItem(Fluocode));
this._navigator.addScreen( "Main", new ScreenNavigatorItem(AppMain));
this._navigator.showScreen("Fluocode");
this._transitionManager.duration = 0.5;
this._transitionManager.ease = Transitions.EASE_IN;
}

Windows phone 8.0 change background several times

I need to change the background color several times during one event , currently I am doing this
LayoutRoot.Background = new SolidColorBrush( Colors.Cyan );
and its changing the color.
but I want it to be like this
LayoutRoot.Background = new SolidColorBrush( Colors.Cyan );
System.Threading.Thread.Sleep(2000);
LayoutRoot.Background = new SolidColorBrush( Colors.White );
but the problem that the 2nd piece of code changes directly to white , because the change occurs when the execution is done , I want it to be done while the code is executing , any ideas for that ?
int state;
// Constructor
public MainPage()
{
state = 0;
// create our dispatch timer
DispatcherTimer timer;
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(2000);
timer.Tick += OnTimerTick;
timer.Start();
// timer.Stop(); // call this to stop
}
// if the timer is on, cycle the color
private void OnTimerTick(object sender, EventArgs e)
{
try
{
if(state == 0){
LayoutRoot.Background = new SolidColorBrush( Colors.Cyan );
state = 1;
}
else
{
LayoutRoot.Background = new SolidColorBrush( Colors.White );
state = 0;
}
}
catch (Exception ex)
{
string error_message = ex.Message;
}
}

Add fixed MapLayer once

In my application I have a map for which the first thing I do (on launching) is to add a custom MapLayer (which I populate with many MapOverlays/pushpins).
When I browse to another page of the app and then return to the map page, everything (ie the MapLayer that was drawn on my map) is gone.
It takes time to add it all over again each time the user navigates to the map page so I would like it to be fixed, drawn/added just once.
Any suggestions?
edit, added the code [I removed some details, the structure remains the same]:
private async void drawStations()
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("stasy.sqlite");
List<line1_stations> lines = await conn.QueryAsync<line1_stations>("select *...");
Microsoft.Phone.Maps.Controls.MapLayer layer = new Microsoft.Phone.Maps.Controls.MapLayer();
Pushpin p;
foreach (line1_stations a in lines)
{
double sLat = Convert.ToDouble(a.lat);
double sLon = Convert.ToDouble(a.lon);
p = new Pushpin();
p.Location = new GeoCoordinate(sLat, sLon);
p.Tap += img_Tap;
p.Content = "...";
p.Foreground = new SolidColorBrush(Colors.Transparent);
p.Width = 30;
p.Height = 30;
MapOverlay overlay1 = new MapOverlay();
overlay1.Content = p;
overlay1.GeoCoordinate = new GeoCoordinate(sLat, sLon);
overlay1.PositionOrigin = new Point(0.0, 1.0);
layer.Add(overlay1);
}
myMap.Layers.Add(layer);
}
You can try to create your MapLayer as a public property in App.xaml.cs and set it only when your app is running first time.
Then create an instance of app inside page with your map and add your MapLayer to your Map layers inside OnNavigatedTo event.
Define a flag in app level. here is the sample
// In App.xaml.cs
public static bool IsLaunched = false;
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsLaunched =true;
}
//In your map screen
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if(App.IsLaunched)
{
drawStations();
//Set App flage to false
App.IsLaunched = false;
}
}
private async void drawStations()
{
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("stasy.sqlite");
List<line1_stations> lines = await conn.QueryAsync<line1_stations>("select *...");
Microsoft.Phone.Maps.Controls.MapLayer layer = new Microsoft.Phone.Maps.Controls.MapLayer();
Pushpin p;
foreach (line1_stations a in lines)
{
double sLat = Convert.ToDouble(a.lat);
double sLon = Convert.ToDouble(a.lon);
p = new Pushpin();
p.Location = new GeoCoordinate(sLat, sLon);
p.Tap += img_Tap;
p.Content = "...";
p.Foreground = new SolidColorBrush(Colors.Transparent);
p.Width = 30;
p.Height = 30;
MapOverlay overlay1 = new MapOverlay();
overlay1.Content = p;
overlay1.GeoCoordinate = new GeoCoordinate(sLat, sLon);
overlay1.PositionOrigin = new Point(0.0, 1.0);
layer.Add(overlay1);
}
myMap.Layers.Add(layer);
}

How to refine strokes of an inkpresenter WP8

I'm using ink presenter to draw the strokes. But the problem is while drawing curved lines, its draws jagged lines.. Straight lines do not have a problem. This is how I have done.. I dont know where to make changes so as to make the lines smoother.
private void MyIP_MouseLeftButtonDown(object sender, MouseEventArgs e)
{
MyIP.CaptureMouse();
DrawingAttributes att = new DrawingAttributes();
att.Color = CB;
att.Width = StrokeWidth;
att.Height = StrokeWidth;
if (bErase == true)
{
StylusPointCollection ErasePointCollection = new StylusPointCollection();
ErasePointCollection.Add(e.StylusDevice.GetStylusPoints(MyIP));
lastPoint = ErasePointCollection[ErasePointCollection.Count - 1];
EraseStroke = new Stroke(ErasePointCollection);
EraseStroke.DrawingAttributes = att;
}
else
{
StylusPointCollection MyStylusPointCollection = new StylusPointCollection();
MyStylusPointCollection.Add(e.StylusDevice.GetStylusPoints(MyIP));
NewStroke = new Stroke(MyStylusPointCollection);
NewStroke.DrawingAttributes = att;
MyIP.Strokes.Add(NewStroke);
}
}
//StylusPoint objects are collected from the MouseEventArgs and added to MyStroke.
private void MyIP_MouseMove(object sender, MouseEventArgs e)
{
if (bErase == true)
{
//StylusPointCollection pointErasePoints = e.StylusDevice.GetStylusPoints(MyIP);
//EraseStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(MyIP));
//pointErasePoints.Insert(0, lastPoint);
//StrokeCollection hitStrokes = MyIP.Strokes.HitTest(pointErasePoints);
//if (hitStrokes.Count > 0)
//{
// foreach (Stroke hitStroke in hitStrokes)
// {
// ////For each intersecting stroke, split the stroke into two while removing the intersecting points.
// ProcessPointErase(hitStroke, pointErasePoints);
// }
//}
//lastPoint = pointErasePoints[pointErasePoints.Count - 1];
//STROKEERASE METHOD
StylusPointCollection pointErasePoints = e.StylusDevice.GetStylusPoints(MyIP);
StrokeCollection hitStrokes = MyIP.Strokes.HitTest(pointErasePoints);
if (hitStrokes.Count > 0)
{
foreach (Stroke hitStroke in hitStrokes)
{
MyIP.Strokes.Remove(hitStroke);
undoStack.Push(hitStroke);
undoStateBufferStack.Push(true);
}
}
}
if (NewStroke != null)
NewStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(MyIP));
}
//MyStroke is completed
private void MyIP_LostMouseCapture(object sender, MouseEventArgs e)
{
if (NewStroke != null)
{
undoStack.Push(NewStroke);
undoStateBufferStack.Push(false);
}
EraseStroke = null;
NewStroke = null;
}
//Set the Clip property of the inkpresenter so that the strokes
//are contained within the boundary of the inkpresenter
private void SetBoundary()
{
RectangleGeometry MyRectangleGeometry = new RectangleGeometry();
MyRectangleGeometry.Rect = new Rect(0, 0, MyIP.ActualWidth, MyIP.ActualHeight);
MyIP.Clip = MyRectangleGeometry;
}
You can find the sample source code describing ink presenter in this Download link
. Please find the download tag. Also it contains plenty other samples which helps you to learn windows phone deeper.