Draw polygon on MapBox map in Xamarin forms - xamarin

I am using Mapbox for Xamarin.Forms NuGet to implement MapBox on Xamarin forms.
But I am not able to draw polygon on map.
Code:
Naxam.Controls.Mapbox.Forms.PolylineAnnotation polyline = null;
if (polyline == null)
{
polyline = new Naxam.Controls.Mapbox.Forms.PolylineAnnotation
{
HexColor = “#ff1234”,
Width = 100
};
}
// Set coordinates
List<CompanyGeoFenceVM> cordinates = new List<CompanyGeoFenceVM>();
var savedCordinates = Preferences.Get(“cordinates”, “”);
if (!string.IsNullOrEmpty(savedCordinates))
{
cordinates = JsonConvert.DeserializeObject<List<CompanyGeoFenceVM>>(savedCordinates);
}
foreach (var cordinate in cordinates)
{
if (polyline.Coordinates == null)
{
polyline.Coordinates = new ObservableCollection<Naxam.Controls.Mapbox.Forms.Position>
{ new Naxam.Controls.Mapbox.Forms.Position(cordinate.Latitude, cordinate.Longitude) };
}
else
{
(polyline.Coordinates as ObservableCollection<Naxam.Controls.Mapbox.Forms.Position>)
.Add(new Naxam.Controls.Mapbox.Forms.Position(cordinate.Latitude, cordinate.Longitude));
}
}
List<Naxam.Controls.Mapbox.Forms.PolylineAnnotation> polylineAnnotations = new List<Naxam.Controls.Mapbox.Forms.PolylineAnnotation>();
polylineAnnotations.Add(polyline);
//show polygon
map.Polylines = polylineAnnotations;
map.ZoomLevel = Device.RuntimePlatform == Device.Android ? 8 : 10;
Xamarin.Forms.Maps.Position position = await NexgenGeocoder.ReverseGeocode(Preferences.Get(“address”, “”));
map.Center = new Naxam.Controls.Mapbox.Forms.Position(position.Latitude , position.Longitude);
Here i am trying to add the polygon. cordinate is variable which has the coodinates required data to process. kindly help me on this. Thank you.

Included Naxam nuget package and plotted the polygon using Polyline. At last need to add a custom line to complete the Polyline area.
Naxam.Controls.Mapbox.Forms.PolylineAnnotation polyline = null;
ObservableCollection<Naxam.Controls.Mapbox.Forms.Annotation> annotations;
annotations = new ObservableCollection<Naxam.Controls.Mapbox.Forms.Annotation>();
//Add Polygon
if (polyline == null)
{
polyline = new Naxam.Controls.Mapbox.Forms.PolylineAnnotation
{
Id = "my_polyline",
Title = "Polygon",
HexColor = "#ff1234",
Width = 1
};
}
foreach (var cordinate in cordinates)
{
if (polyline.Coordinates == null)
{
polyline.Coordinates = new ObservableCollection<Naxam.Controls.Mapbox.Forms.Position>
{ new Naxam.Controls.Mapbox.Forms.Position(cordinate.Latitude, cordinate.Longitude) };
}
else
{
(polyline.Coordinates as ObservableCollection<Naxam.Controls.Mapbox.Forms.Position>)
.Add(new Naxam.Controls.Mapbox.Forms.Position(cordinate.Latitude, cordinate.Longitude));
}
}
//We are using polylines so we have to add ending point to line.
if (polyline.Coordinates != null)
(polyline.Coordinates as ObservableCollection<Naxam.Controls.Mapbox.Forms.Position>)
.Add(new Naxam.Controls.Mapbox.Forms.Position(cordinates[0].Latitude, cordinates[0].Longitude));
annotations.Add(polyline);
mapview.Annotations = annotations;

Related

Xamarin.Forms ZXing BarcodeReaderGeneric returns null when scanning an image in the gallery

I am developing a barcode reader with Xamarin.Forms. And I'm trying to scan the image on Android device.
First I select the image from the gallery with Xamarin.Essentials MediaPicker and from the path of this image I get an RGBLuminance with the Dependency class.
Then I am trying to decode this RGBLuminance with the Decode() method of the ZXing BarcodeReaderGeneric class. However, the result always returns null.
It is my demo project : https://onedrive.live.com/?authkey=%21AFLjjM91wgZkBGU&cid=58BE2C2C3447FFA2&id=58BE2C2C3447FFA2%219829&parId=root&action=locate
Command in the ViewModel class:
public ICommand PickCommand => new Command(PickImage);
private async void PickImage()
{
var pickResult = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
{
Title = "Select a barcode."
});
var path = pickResult.FullPath;
var RGBLuminance = DependencyService.Get<ILuminance>().GetRGBLuminanceSource(path);
var reader = new BarcodeReaderGeneric();
var result = reader.Decode(RGBLuminance); // result always null.
}
Method of Dependency class in Android:
public RGBLuminanceSource GetRGBLuminanceSource(string imagePath)
{
if (File.Exists(imagePath))
{
Android.Graphics.Bitmap bitmap = BitmapFactory.DecodeFile(imagePath);
List<byte> rgbBytesList = new List<byte>();
for (int y = 0; y < bitmap.Height; y++)
{
for (int x = 0; x < bitmap.Width; x++)
{
var c = new Android.Graphics.Color(bitmap.GetPixel(x, y));
rgbBytesList.AddRange(new[] { c.A, c.R, c.G, c.B });
}
}
byte[] rgbBytes = rgbBytesList.ToArray();
return new RGBLuminanceSource(rgbBytes, bitmap.Height, bitmap.Width, RGBLuminanceSource.BitmapFormat.RGB32);
}
return null;
}
You should change the line
return new RGBLuminanceSource(rgbBytes, bitmap.Height, bitmap.Width, RGBLuminanceSource.BitmapFormat.RGB32);
to
return new RGBLuminanceSource(rgbBytes, bitmap.Width, bitmap.Height, RGBLuminanceSource.BitmapFormat.RGB32);
And to be more accurate with the RGB format you should
change RGBLuminanceSource.BitmapFormat.RGB32 to RGBLuminanceSource.BitmapFormat.ARGB32
or change rgbBytesList.AddRange(new[] { c.A, c.R, c.G, c.B }); to rgbBytesList.AddRange(new[] { c.R, c.G, c.B, c.A });
Can you try with this pictures?
Picture One
Picture Two

Unable to add an Image to a powerpoint presentation using open xml

I am using the following code to add a new slide to a ppt file and add an image. I am using Open XML 2.5 SDK.
A new slide is getting added but not the image. Is there anything wrong in this code?
int position = 1;
using (PresentationDocument presentationDocument = PresentationDocument.Open("c.pptx", true))
{
PresentationPart presentationPart = presentationDocument.PresentationPart;
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
// Specify the group shape properties of the new slide.
slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
// Create the slide part for the new slide.
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
// Save the new slide part.
slide.Save(slidePart);
string imgId = "rId" + new Random().Next(2000).ToString();
ImagePart imagePart = slidePart.AddImagePart(ImagePartType.Png, imgId);
using (FileStream stream = new FileStream("a.png", FileMode.Open))
{
stream.Position = 0;
imagePart.FeedData(stream);
}
slide.Save(slidePart);
// Modify the slide ID list in the presentation part.
// The slide ID list should not be null.
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
// Find the highest slide ID in the current list.
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
}
position--;
if (position == 0)
{
prevSlideId = slideId;
}
}
maxSlideId++;
// Get the ID of the previous slide.
SlidePart lastSlidePart;
if (prevSlideId != null)
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
}
else
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
}
// Use the same slide layout as that of the previous slide.
if (null != lastSlidePart.SlideLayoutPart)
{
slidePart.AddPart(lastSlidePart.SlideLayoutPart);
}
// Insert the new slide into the slide list after the previous slide.
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
// Save the modified prsentation.
presentationPart.Presentation.Save();
Thanks in advance.

Flash AS2 - grouping enemies

So I have a Flash ActionScript 2 code, which creates a preset amount of enemies, gives enemies stats, and makes them move around randomly. Code:
//Settings
var mapWidth:Number = 550;
var mapHeight:Number = 400;
var enemiesArray:Array = new Array();
var totalEnemies:Number;
var eClip:MovieClip;
//Math functions
function getdistance(x, y, x1, y1)
{
run = x1-x;
rise = y1-y;
return (hyp(run, rise));
}
function hyp(a, b)
{
return (Math.sqrt(a*a+b*b));
}
function resetDirection(mc:MovieClip)
{
mc.roamTime = random(50);
mc.t = mc.roamTime;
mc.roamDistance = random(60)+25;
mc.randomRoamDistanceX = (Math.random()*mc.roamDistance)+mc.xx-(mc.roamDistance/2);
mc.randomRoamDistanceY = (Math.random()*mc.roamDistance)+mc.yy-(mc.roamDistance/2);
mc.newRoamDistance = getdistance(mc._x, mc._y, mc.randomRoamDistanceX, mc.randomRoamDistanceY);
mc.norm = mc.roamSpeed/mc.newRoamDistance;
mc.finalRoamDistanceX = (mc.randomRoamDistanceX-mc.xx)*mc.norm;
mc.finalRoamDistanceY = (mc.randomRoamDistanceY-mc.yy)*mc.norm;
}
//function to move enemies
function moveIt(mc:MovieClip)
{
//reduce roamTime;
mc.t--;
//move enemy to new position
if (getdistance(mc._x, mc._y, mc.randomRoamDistanceX, mc.randomRoamDistanceY)>mc.roamSpeed) {
mc._x += mc.finalRoamDistanceX;
mc._y += mc.finalRoamDistanceY;
}
//rotate enemy
XXXdiff = mc.xx-mc.randomRoamDistanceX;
YYYdiff = -(mc.yy-mc.randomRoamDistanceY);
rrradAngle = Math.atan(YYYdiff/XXXdiff);
if (XXXdiff<0) {
cccorrFactor = 270;
} else {
cccorrFactor = 90;
}
//
mc.ship_mc._rotation = -(rrradAngle*360/(2*Math.PI)+cccorrFactor);
//check if time to reset, based on roamTime
if (mc.t<=0) {
resetDirection(mc);
}
}
//
// Generate Enemies
//
// set and save enemy stats
//
//
// createEnemies(number of enemies you want, movieclip where you want to create the enemies);
//
function createEnemies(amount:Number, targetLocation:MovieClip) {
trace("createEnemies: "+amount);
for (var i = 0; i<amount; i++) {
randomXpos = Math.round(Math.random()*mapWidth);
randomYpos = Math.round(Math.random()*mapHeight);
//add new enemy to map
var newEnemy:MovieClip = targetLocation.attachMovie("enemy1", "enemy1_"+i, targetLocation.getNextHighestDepth());
enemiesArray.push(newEnemy);
//
//set enemy stats
newEnemy.id = i;
newEnemy._x = randomXpos;
newEnemy._y = randomYpos;
//save x and y position
newEnemy.xx = newEnemy._x;
newEnemy.yy = newEnemy._y;
//
newEnemy.roamSpeed = 2
newEnemy.roamTime = random(50);
newEnemy.roamDistance = random(60)+25;
newEnemy.t = 0;
//
newEnemy.myHealth = 10;
newEnemy.myName = "Small Scout";
//
resetDirection(newEnemy);
//target enemy
newEnemy.onPress = function() {
trace("Enemy: "+this.tName+" "+this.id);
target_txt.text = this.myName+": "+this.id+" Health: "+this.myHealth;
};
newEnemy.onEnterFrame = function() {
moveIt(this);
};
}
}
start_btn.onRelease = function() {
if (start_txt.text == "Start") {
//run the create enemies function to start the engine
createEnemies(box_mc.numberOfEnemies.text, map_mc);
//hide start button
start_txt._visible =false;
this._visible = false;
box_mc._visible = false;
}
};
I want program enemies to be grouped (based on fireflies algorithm). My idea is write for loop to define attractiveness, but I don't know how to make my objects move to the most attractiveness. Maybe someone would help me with this problem?
I change this line:
newEnemy.myHealth = 10;
on this
newEnemy.myHealth = Math.round(random(9)+1);
myHealth would be responsible for attractiveness. I try to use code from this site and modificate code to let objects with low attractiveness follow objects with large attractiveness. Also, I want to stop algorith, when they are in the groups.

Inserting image in PPTX using OpenXML does not work

I am trying to generate a PowerPoint file containing a image using OpenXML. Unfortunately it does not work. The image is not being displayed. I've checked the file generated with the OpenXML productivity tool and I respectively unzipped the file contents. The file itself contains the image in /ppt/media/image.png and it should be displayed in the second slide.
Here's my code:
private void InsertSlide(string chartString, int position, string title, string text = "")
{
if (m_presentation == null || title == null || m_presentation.PresentationPart == null)
return;
var slide = new Slide(new CommonSlideData(new ShapeTree()));
var nonVisualProperties =
slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties { Id = 1, Name = "" };
nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
var slidePart = m_presentation.PresentationPart.AddNewPart<SlidePart>();
var imagePart = slidePart.AddImagePart(ImagePartType.Png, "irgendeinscheiss");
//var imageStream = new MemoryStream(Convert.FromBase64String(chartString));
using (var imageStream = new FileStream(#"C:\Users\DA\Desktop\Charts\1_Chart2_01.png", FileMode.Open))
{
imageStream.Position = 0;
imagePart.FeedData(imageStream);
}
slide.Save(slidePart);
var slideIdList = m_presentation.PresentationPart.Presentation.SlideIdList;
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
maxSlideId = slideId.Id;
position--;
if (position == 0)
prevSlideId = slideId;
}
maxSlideId++;
SlidePart lastSlidePart;
if (prevSlideId != null)
lastSlidePart = (SlidePart)m_presentation.PresentationPart.GetPartById(prevSlideId.RelationshipId);
else
lastSlidePart = (SlidePart)m_presentation.PresentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
if (lastSlidePart.SlideLayoutPart != null)
slidePart.AddPart(lastSlidePart.SlideLayoutPart);
var newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = m_presentation.PresentationPart.GetIdOfPart(slidePart);
m_presentation.PresentationPart.Presentation.Save();
}
Am I missing something? Maybe the relationships? After looking up 232243 thousand different examples, I am still stuck at this point. Thank you!
I think you need to add the image into the slide.CommonSlideData
public Slide InsertSlide(PresentationPart presentationPart, string layoutName)
{
UInt32 slideId = 256U;
// Get the Slide Id collection of the presentation document
var slideIdList = presentationPart.Presentation.SlideIdList;
if (slideIdList == null)
{
throw new NullReferenceException("The number of slide is empty, please select a ppt with a slide at least again");
}
slideId += Convert.ToUInt32(slideIdList.Count());
// Creates an Slide instance and adds its children.
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
slide.Save(slidePart);
// Get SlideMasterPart and SlideLayoutPart from the existing Presentation Part
SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();
SlideLayoutPart slideLayoutPart = slideMasterPart.SlideLayoutParts.SingleOrDefault
(sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName, StringComparison.OrdinalIgnoreCase));
if (slideLayoutPart == null)
{
throw new Exception("The slide layout " + layoutName + " is not found");
}
slidePart.AddPart<SlideLayoutPart>(slideLayoutPart);
slidePart.Slide.CommonSlideData = (CommonSlideData)slideMasterPart.SlideLayoutParts.SingleOrDefault(
sl => sl.SlideLayout.CommonSlideData.Name.Value.Equals(layoutName)).SlideLayout.CommonSlideData.Clone();
// Create SlideId instance and Set property
SlideId newSlideId = presentationPart.Presentation.SlideIdList.AppendChild<SlideId>(new SlideId());
newSlideId.Id = slideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
return GetSlideByRelationShipId(presentationPart, newSlideId.RelationshipId);
}
/// <summary>
/// Get Slide By RelationShip ID
/// </summary>
/// <param name="presentationPart">Presentation Part</param>
/// <param name="relationshipId">Relationship ID</param>
/// <returns>Slide Object</returns>
private static Slide GetSlideByRelationShipId(PresentationPart presentationPart, StringValue relationshipId)
{
// Get Slide object by Relationship ID
SlidePart slidePart = presentationPart.GetPartById(relationshipId) as SlidePart;
if (slidePart != null)
{
return slidePart.Slide;
}
else
{
return null;
}
}
Public void InsertImageInLastSlide(Slide slide, string imagePath, string imageExt)
{
// Creates an Picture instance and adds its children.
P.Picture picture = new P.Picture();
string embedId = string.Empty;
embedId = "rId" + (slide.Elements().Count() + 915).ToString();
P.NonVisualPictureProperties nonVisualPictureProperties = new P.NonVisualPictureProperties(
new P.NonVisualDrawingProperties() { Id = (UInt32Value)4U, Name = "Picture 5" },
new P.NonVisualPictureDrawingProperties(new A.PictureLocks() { NoChangeAspect = true }),
new ApplicationNonVisualDrawingProperties());
P.BlipFill blipFill = new P.BlipFill();
Blip blip = new Blip() { Embed = embedId };
// Creates an BlipExtensionList instance and adds its children
BlipExtensionList blipExtensionList = new BlipExtensionList();
BlipExtension blipExtension = new BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };
UseLocalDpi useLocalDpi = new UseLocalDpi() { Val = false };
useLocalDpi.AddNamespaceDeclaration("a14",
"http://schemas.microsoft.com/office/drawing/2010/main");
blipExtension.Append(useLocalDpi);
blipExtensionList.Append(blipExtension);
blip.Append(blipExtensionList);
Stretch stretch = new Stretch();
FillRectangle fillRectangle = new FillRectangle();
stretch.Append(fillRectangle);
blipFill.Append(blip);
blipFill.Append(stretch);
// Creates an ShapeProperties instance and adds its children.
P.ShapeProperties shapeProperties = new P.ShapeProperties();
A.Transform2D transform2D = new A.Transform2D();
A.Offset offset = new A.Offset() { X = 457200L, Y = 1524000L };
A.Extents extents = new A.Extents() { Cx = 8229600L, Cy = 5029200L };
transform2D.Append(offset);
transform2D.Append(extents);
A.PresetGeometry presetGeometry = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList = new A.AdjustValueList();
presetGeometry.Append(adjustValueList);
shapeProperties.Append(transform2D);
shapeProperties.Append(presetGeometry);
picture.Append(nonVisualPictureProperties);
picture.Append(blipFill);
picture.Append(shapeProperties);
slide.CommonSlideData.ShapeTree.AppendChild(picture);
// Generates content of imagePart.
ImagePart imagePart = slide.SlidePart.AddNewPart<ImagePart>(imageExt, embedId);
FileStream fileStream = new FileStream(imagePath, FileMode.Open);
imagePart.FeedData(fileStream);
fileStream.Close();
}
Source Code

Datagridview - drawing rectangle on datagridview problem c# windows forms

I have 3 questions:
wheter I am doing my task in a good way
why when I scroll dataGridView, painted rectangles dissapear..
why painting is so slow...
Here is the code in which I want to draw a colorful rectangle with text on groups of cells in each column, that have the same values, empty values shouldn't have rectangles
void DataGridView1CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
foreach (DataGridViewColumn column in this.dataGridView1.Columns){
string tempCellValue = string.Empty;
int tempRectX = -1;
int tempRectY = -1;
int tempRectYEnd = -1;
int tempRectWidth = -1;
int tempRectHeight = -1;
foreach (DataGridViewRow row in this.dataGridView1.Rows){
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(
column.Index, row.Index,true);
DataGridViewCell cell = dataGridView1.Rows[row.Index].Cells[column.Index];
if ( cell.Value!=null){
if (tempRectX==-1){
tempRectX = rect.Location.X;
tempRectY = rect.Location.Y;
tempCellValue = cell.Value.ToString();
}else
if (cell.Value.ToString()!=tempCellValue){
tempRectYEnd = rect.Location.Y;
Rectangle newRect = new Rectangle(tempRectX,
tempRectY , 5 ,
tempRectYEnd );
using (
Brush gridBrush = new SolidBrush(Color.Coral),
backColorBrush = new SolidBrush(Color.Coral))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
e.Graphics.FillRectangle(backColorBrush,newRect);
} }
tempRectX=-1;
tempCellValue = string.Empty;
}
}else if (tempRectX!=-1){
tempRectYEnd = rect.Location.Y;
Rectangle newRect = new Rectangle(tempRectX,
tempRectY , 50 ,
tempRectYEnd );
using (
Brush gridBrush = new SolidBrush(Color.Coral),
backColorBrush = new SolidBrush(Color.Coral))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
e.Graphics.FillRectangle(backColorBrush,newRect);
} }
tempRectX=-1;
tempCellValue = string.Empty;
}
}}
The DataGridView1CellPainting event is intended to Paint or change Paint behaviour for one cell.
DGV raises this event for each visible Cell.
When Paint other cells, your code slow down.
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcellpaintingeventargs.aspx

Resources