I want to create an app for airplane navigation. Since for pilots the Bing maps are useless I need to create my own map a texture of an aeronautical map.
I couldn't find any clue how to start on this. Is there an SDK for Bing maps where I can create my own texture/overlay?
Do I need to start from rock bottom and create a picture and change its position so the relevant part is in the visible area of the device?
I need the following features:
Show current position on the map.
Add some custom POIs via coordinates
After quite some research I figured it out myself.
Here is most of the code needed if you have the same scenario
Uri format:
"https://webserver/tiles/{zoomlevel}/{x}/{y}.png";
private void InitMap()
{
_gps = new Geolocator();
pointBuffer = cologne;
image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/images/airplane.png"));
MyMap.Style = MapStyle.None;
//Setup Icao Layer
_icaoTileSource = new MapTileSource();
var _tileLayer = new HttpMapTileDataSource();
_tileLayer.UriFormatString = IcaoUri;
_icaoTileSource.DataSource = _tileLayer;
MyMap.TileSources.Add(_icaoTileSource);
//Setup VFR Layer
_vfrTileSource = new MapTileSource();
var _vfrtileLayer = new HttpMapTileDataSource();
_vfrtileLayer.UriFormatString = VfrUri;
_vfrTileSource.DataSource = _vfrtileLayer;
//Setup Low Level Layer
_lowlvlTileSource = new MapTileSource();
var _lowlvltileLayer = new HttpMapTileDataSource();
_lowlvltileLayer.UriFormatString = LowLvlUri;
_lowlvlTileSource.DataSource = _lowlvltileLayer;
airplane = new MapIcon()
{
Title = "My Position",
Image = image,
Visible = true,
Location = cologne,
NormalizedAnchorPoint = new Point(0.5, 0.5)
};
_tileLayer.AllowCaching = true;
MyMap.MapElements.Add(airplane);
systemSetCenter = true;
MyMap.Center = cologne;
MyMap.ZoomLevel = 10;
_vm.ZoomLevel = MyMap.ZoomLevel;
MyMap.ZoomLevelChanged += (s, e) =>
{
if(s.ZoomLevel > maxZoomLevel)
{
s.ZoomLevel = maxZoomLevel;
}
_vm.ZoomLevel = s.ZoomLevel;
};
}
Related
The IMapViewDelegate apparently isn't a complete C# implementation of MapViewDelegate from objC. That inhibits the access to markerInfoContents delegate method.
I'd like to do something like this allowing me to custom the contentView layout and the tap action
got from: http://www.raywenderlich.com/81103/introduction-google-maps-ios-sdk-swift
I think i can explan its from scratch to add a Custom MarkerInfo Window on the Tap of a Marker. Iam using Xamarin.Google.iOS.Maps package from Official Nuget Library for adding Google Map on my Xamarin MVVM Cross Touch Project.
private void SetupMap()
{
if (_mapView != null)
_mapView.RemoveFromSuperview ();
//Init Map wiht Camera
var camera = new CameraPosition(new CLLocationCoordinate2D(36.069082, -94.155976), 15, 30, 0);
_mapView = MapView.FromCamera(RectangleF.Empty, camera);
_mapView.MyLocationEnabled = true;
//Add button to zoom to location
_mapView.Settings.MyLocationButton = true;
_mapView.MyLocationEnabled = true;
_mapView.Settings.SetAllGesturesEnabled(true);
var xamMarker = new Marker () {
Title = "Sample",
Snippet = "Sample Location",
Position = new CLLocationCoordinate2D (36.069082, -94.155976),
Map = _mapView
};
var xamMarker1 = new Marker () {
Title = "Sample1",
Snippet = "Sample Location2",
Position = new CLLocationCoordinate2D (35.069082, -94.155976),
Map = _mapView
};
_mapView.TappedMarker = (map, marker) => {
Console.WriteLine("Marker tapped:"+ map +"::"+marker);
_mapView.MarkerInfoWindow = new GMSInfoFor(markerInfoWindow);
return false;
};
_mapView.Frame = this.contentViewOutlet.Bounds;
this.contentViewOutlet.AddSubview (_mapView);
_mapView.InfoTapped += (object sender, GMSMarkerEventEventArgs e) => {
Console.WriteLine ("Marker Info tapped:"+e+"::"+sender);
UIAlertView alert = new UIAlertView () {
Title = "Alert", Message = sampleLongandLat
};
alert.AddButton("OK");
alert.Show ();
};
}
you can call this SetupMap() method from where ever you want. for example in ViewDidLoad or from any where you have to add the google map.
On click or Tap of the marker we are creating a custom marker window
_mapView.TappedMarker = (map, marker) => {
Console.WriteLine("Marker tapped:"+ map +"::"+marker);
_mapView.MarkerInfoWindow = new GMSInfoFor(markerInfoWindow);
return false;
};
the above code is included in the SetupMap method.
mapView.MarkerInfoWindow = new GMSInfoFor(markerInfoWindow); these above line of code will allow us to load a custom Marker Window instead of the default one
UIView markerInfoWindow(UIView view, Marker marker)
{
// use this method to return the custom view u have already created to load as a subview in Google Map as Custom Marker Info Windo
UIView v;
v = MarkerInfoView.Create(marker);
sampleLongandLat = MarkerInfoView.markerInfoString;
sampleLongandLat = MarkerInfoView.locationIDString;
return v;
}
for adding an custom UIView you can follow the example provided in the xamarin web site loading an xib or UIView in another ViewController as a sub view
_mapView.InfoTapped += (object sender, GMSMarkerEventEventArgs e) => {
Console.WriteLine ("Marker Info tapped:"+e+"::"+sender);
UIAlertView alert = new UIAlertView () {
Title = "Alert", Message = sampleLongandLat
};
alert.AddButton("OK");
alert.Show ();
};
the above code snippet you can use for detecting tap on the Marker Info Window
I've done quite a bit of searching, so please forgive me if this has been asked before (I couldn't seem to find the right phrasing, if this is the case).
I have converted a quiz game from Flash to html5 using the createjs suite of libraries, and it is functioning suitably well on android devices and iPhones (tested on an iPhone 4s and 5c). However, it appears to be crashing on an iPad whenever I try and load it.
As I am packaging the game in cocoonjs for mobile deployment, I first thought the issue lied somewhere in the conversion process, but the same issue is encountered when I visit the URL on an iPad, leading me to believe the issue must be somewhere in my code.
The code itself uses a loadManifest to preload the image assets for the game and the opening audio file. There are approximately 170 assets loaded in this queue. The files are loaded using an onLoad method from the body tag and call loadFiles(), which looks like this (truncated for the multitude of image assets loaded in the manifest):
var queue = new createjs.LoadQueue(true);
var manifest = [
{id:"gameintro", src:"audio/intro.mp3"},
{src:"images/Path.png"},
...
{src:"images/owl.png"}
];
queue.loadManifest(manifest);
queue.setMaxConnections(5);
queue.addEventListener("complete", loadComplete);
function loadAll() {
document.getElementById('canvas').style.backgroundImage="url('images/splash.png')";
canvas = document.getElementById('canvas');
canvas.height = H;
canvas.width = W;
stage = new createjs.Stage("canvas");
var loadingText = new createjs.Text("Loading...", "bold 30px Arial", "#9d3202");
loadingText.x = 350;
loadingText.y = 585;
loadingText.textBaseline = "alphabetic";
stage.addChild(loadingText);
stage.update();
while (manifest.length > 0) {
loadAnother();
}
//console.log('done');
}
function loadAnother() {
// Get the next manifest item, and load it
var item = manifest.shift();
queue.loadFile(item);
// If we have no more items, disable the UI.
if (manifest.length == 0) {
//do nothing
}
}
function loadComplete()
{
stage.removeAllChildren();
var clickToPlay = new createjs.Bitmap("images/clicktoplay.png");
clickToPlay.x = 350;
clickToPlay.y = 565;
clickToPlay.textBaseline = "alphabetic";
stage.addChild(clickToPlay);
stage.update();
canvas.addEventListener("click", function(event) {
event.target.removeEventListener(event.type, arguments.callee);
createjs.Sound.registerSound({id:"gameintro", src:"audio/intro.mp3"});
createjs.Sound.addEventListener("fileload", function(event){
event.target.removeEventListener(event.type, arguments.callee);
init();
});
});
}
loadAll();
};
The init function that runs after this loads the remaining audio files (of which there are many ~ 160 mp3's) and starts the opening animation. The code for that section is as follows:
function init(){
createjs.Sound.registerSound({id:"meintroduction", src:"audio/Mentor/ME1.mp3"});
...
createjs.Sound.registerSound({id:"jennyfalse3", src:"audio/Pirate_Jenny/PJE10.mp3"});
document.getElementById('canvas').style.background="#B5D7ED";
canvas = document.getElementById('canvas');
canvas.height = H;
canvas.width = W;
stage = new createjs.Stage("canvas");
//add path
path = new createjs.Bitmap("images/Path.png");
path.x = 0;
path.y = 0;
stage.addChild(path);
//add sun
sun = new createjs.Bitmap("images/sun.png");
sun.x = 800;
sun.y = 600;
stage.addChild(sun);
//add pinkcloud
pinkcloud = new createjs.Bitmap("images/pinkcloud.png");
pinkcloud.x = -4;
pinkcloud.y = 150;
stage.addChild(pinkcloud);
//add bluecloud
bluecloud = new createjs.Bitmap("images/bluecloud.png");
bluecloud.x = -4;
bluecloud.y = 250;
stage.addChild(bluecloud);
//add farisland
farisland = new createjs.Bitmap("images/farisland.png");
farisland.x = 600;
farisland.y = 180;
stage.addChild(farisland);
//add backwave
backwave = new createjs.Bitmap("images/backwave.png");
backwave.x = -4;
backwave.y = 420;
stage.addChild(backwave);
//shark
shark = new createjs.Bitmap("images/shark.png");
shark.x = 900;
shark.y = 600;
stage.addChild(shark);
//fish3
fish3 = new createjs.Bitmap("images/fish3.png");
fish3.x = 800;
fish3.y = 600;
stage.addChild(fish3);
//add middlewave
middlewave = new createjs.Bitmap("images/middlewave.png");
middlewave.x = -800;
middlewave.y = 450;
stage.addChild(middlewave);
//add ship
pirateship = new createjs.Bitmap("images/pirateship.png");
pirateship.x = -500;
pirateship.y = 400;//445x384
pirateship.regX = 445/2;
pirateship.regY = 384/2;
stage.addChild(pirateship);
//fish1
fish1 = new createjs.Bitmap("images/fish1.png");
fish1.x = 800;
fish1.y = 600;
stage.addChild(fish1);
//fish1
fish2 = new createjs.Bitmap("images/fish2.png");
fish2.x = 900;
fish2.y = 700;
stage.addChild(fish2);
//add frontwave
frontwave = new createjs.Bitmap("images/frontwave.png");
frontwave.x = -4;
frontwave.y = 500;
stage.addChild(frontwave);
//bird
bird1 = new createjs.Bitmap("images/bird.png");
bird1.x = 0;
bird1.y = 0;
bird1.scaleX = -1;
stage.addChild(bird1);
bird2 = new createjs.Bitmap("images/bird.png");
bird2.x = 800;
bird2.y = 0;
stage.addChild(bird2);
//add island
island = new createjs.Bitmap("images/island.png");
island.x = 800;
island.y = 200;
stage.addChild(island);
//add setsail
setsail = new createjs.Bitmap("images/Setsail.png");
setsail.x = -358;
setsail.y = 80;
createjs.Tween.get(setsail).to({alpha: 0,},0);
stage.addChild(setsail);
setsail1 = new createjs.Bitmap("images/Setsail.png");
setsail1.x = 350;
setsail1.y = 80;
//add butwatchout
butwatchout = new createjs.Bitmap("images/Butwatchout.png");
butwatchout.x = -358;
butwatchout.y = 300;
createjs.Tween.get(butwatchout).to({alpha: 0,},0);
//stage.addChild(butwatchout);
butwatchout1 = new createjs.Bitmap("images/Butwatchout.png");
butwatchout1.x = 200;
butwatchout1.y = 300;
setTimeout(function(){createjs.Sound.play("gameintro");},1500);
fn = createjs.Ticker.on("tick", tick);
createjs.Ticker.setFPS(80);
createjs.Ticker.addEventListener("tick", stage );
}
The ticker then uses some basic rotations and tweens to move things about, and also employs some alpha filters to manage the transparency of certain assets (like the front wave on the ship). After all this is finished, the user then progresses into the actual game, which uses some very basic createjs.Bitmaps to add the elements to the stage, along with Sound.play and some SpriteSheets for the rudimentary animations like blinking and mouth-movements for the quizzers. However, the whole thing doesn't make it past the opening sequence on an iPad.
If anyone could take a look (amateurgamingleague.com/pirates/english) and give me a bit of insight as to where I'm messing up, out would be greatly appreciated!!
Thank you!
I have had the same crashes on Ipad (2). It even did delete all session cookies and my users where logged out...
The problem is the amount of sounds you're preloading (or how big they are, not sure). Change your code to not preload so many audio anymore, and load them on demand (when user clicks on something) if possible. I also needed to start the game with a click/touch/user event before any sound could be played.
I got the same issue.
Try to use slash before the directory like
var manifest = [
{id:"gameintro", src:"/audio/intro.mp3"},
{src:"/images/Path.png"},
...
{src:"/images/owl.png"}
];
I am using a tee chart library in xamarin (Android). i am facing a problem to daynamic binding data in "Candle Chart"
The Sample Code Like this!
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
RequestWindowFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.CandleChart);
//InitializeComponent();
chart = new Steema.TeeChart.TChart(this.ApplicationContext);
chart.Zoom.Style = Steema.TeeChart.ZoomStyles.InChart;
Steema.TeeChart.Themes.BlackIsBackTheme myTheme = new Steema.TeeChart.Themes.BlackIsBackTheme(chart.Chart);
myTheme.Apply();
Type tmp = (Type)Steema.TeeChart.Utils.SeriesTypesOf[12];
Steema.TeeChart.Styles.Series series;
series = chart.Series.Add(tmp);
series.FillSampleValues(); /* Here i want to fill series with my data listed bellow */
chart.Aspect.View3D = Needs3D(chart[0]);
chart.Panel.Transparent = true;
SetContentView(chart);
}
now i want add series data manually
like :
currentItem.Data.Close
currentItem.Data.Open
currentItem.Data.High
currentItem.Data.Low
currentItem.Time
etc.. so, plz help me to achieve this ..
thanks, in advance
==================================================================================
My Code Like as Bellow
private void LoadChart(GraphOutput resGraph)
{
DataSet_Obj.Tables.Add("CandleTable");
DataSet_Obj.Tables["CandleTable"].Columns.Add(new DataColumn("Date", System.Type.GetType("System.DateTime")));
DataSet_Obj.Tables["CandleTable"].Columns.Add(new DataColumn("Open", System.Type.GetType("System.Double")));
DataSet_Obj.Tables["CandleTable"].Columns.Add(new DataColumn("Close", System.Type.GetType("System.Double")));
DataSet_Obj.Tables["CandleTable"].Columns.Add(new DataColumn("High", System.Type.GetType("System.Double")));
DataSet_Obj.Tables["CandleTable"].Columns.Add(new DataColumn("Low", System.Type.GetType("System.Double")));
for (int i = 0; i < resGraph.graphSymbol[0].CandleSticks.Length; i++)
{
DataRow_Obj = DataSet_Obj.Tables["CandleTable"].NewRow();
DataRow_Obj["Date"] = resGraph.graphSymbol[0].CandleSticks[i].CandleTime; //DateTime
DataRow_Obj["Low"] = resGraph.graphSymbol[0].CandleSticks[i].CandleData.Low; //Float
DataRow_Obj["Close"] = resGraph.graphSymbol[0].CandleSticks[i].CandleData.Close; //Float
DataRow_Obj["Open"] = resGraph.graphSymbol[0].CandleSticks[i].CandleData.Open; //Float
DataRow_Obj["High"] = resGraph.graphSymbol[0].CandleSticks[i].CandleData.High; //Float
DataSet_Obj.Tables["CandleTable"].Rows.Add(DataRow_Obj);
DataRow_Obj = null;
}
Tag_Serie_Candle = new Steema.TeeChart.Styles.Candle ();
chart.Series.Add(Tag_Serie_Candle);
chart.Aspect.View3D = Needs3D(chart[0]);
chart.Panel.Transparent = true;
try
{
Tag_Serie_Candle.DataSource = DataSet_Obj.Tables["CandleTable"]; /* here I got Error Like: "Cannot bind to non-supported datasource: CandleTable" */
Tag_Serie_Candle.OpenValues.DataMember = DataSet_Obj.Tables["CandleTable"].Columns["Open"].ToString();
Tag_Serie_Candle.CloseValues.DataMember = DataSet_Obj.Tables["CandleTable"].Columns["Close"].ToString();
Tag_Serie_Candle.DateValues.DataMember = DataSet_Obj.Tables["CandleTable"].Columns["Date"].ToString();
Tag_Serie_Candle.DateValues.DateTime = true;
Tag_Serie_Candle.HighValues.DataMember = DataSet_Obj.Tables["CandleTable"].Columns["High"].ToString();
Tag_Serie_Candle.LowValues.DataMember = DataSet_Obj.Tables["CandleTable"].Columns["Low"].ToString();
Tag_Serie_Candle.LabelMember = "Candle Chart";
Tag_Serie_Candle.CheckDataSource();
chartpie.AddView(chart, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent));
}
catch (Exception exe)
{
exe.Message.ToString();
}
}
You should do something as in the examples here:
http://www.teechart.net/support/viewtopic.php?f=4&t=2978&p=10547#p10547
http://www.teechart.net/support/viewtopic.php?f=4&t=3291&p=11691#p11691
http://www.teechart.net/support/viewtopic.php?f=4&t=2741&p=11681#p11681
I have found that, at the present moment, this is not working. I added the defect (ID566) list to be fixed as soon as possible (now fixed, see update at the bottom of the reply). If you register at Steema Software's Bugzilla system, you will be able to be in the CC List and be notified about status updates. In the meantime you can manually read values from the DataSet using this code:
Tag_Serie_Candle.DateValues.DateTime = true;
for (int i = 0; i < DataSet_Obj.Tables["CandleTable"].Rows.Count; i++)
{
DataRow row = DataSet_Obj.Tables["CandleTable"].Rows[i];
DateTime dt = Convert.ToDateTime(row["Date"]);
Double open = Convert.ToDouble(row["Open"]);
Double high = Convert.ToDouble(row["High"]);
Double low = Convert.ToDouble(row["Low"]);
Double close = Convert.ToDouble(row["Close"]);
Tag_Serie_Candle.Add(dt, open, high, low, close);
}
UPDATE: As of 11th February 2014, the defect has been fixed. Anyone interested in testing the solution please let me know.
I am using open XML SDK and I want to move the content of content control (containing images) from the header to the body, the problem that images does not show after moving. After copying the content control content I am adding the image parts in this way :
foreach (var headerPart in wordDocument.MainDocumentPart.HeaderParts)
{
SdtBlock sdtToSave = this.FindSdtBlock(contentControlTag, headerPart );
if (sdtToSave != null)
{
foreach (var imagePart in headerPart.ImageParts)
{
ImagePart newPart = mainPart.AddImagePart(imagePart.ContentType);
this.GenerateImagePartContent(newPart, imagePart.GetStream()); }
}
}
private void GenerateImagePartContent(ImagePart imagePart, Stream partStream)
{
imagePart.FeedData(partStream);
partStream.Close();
}
then if I add this lines :
Paragraph paragraph = sdtToSave.SdtContentBlock.GetFirstChild<Paragraph>();
Run run = new Run();
paragraph.Append(run);
run.Append(this.GenerateDrawing(mainPart.GetIdOfPart(newPart)));
private Drawing GenerateDrawing(String relationshipID)
{
Drawing drawing1 = new Drawing();
Inline inline1 = new Inline() { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U };
Extent extent1 = new Extent() { Cx = 152400L, Cy = 152400L };
EffectExtent effectExtent1 = new EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L };
DocProperties docProperties1 = new DocProperties() { Id = (UInt32Value)1U, Name = "Image 1" };
NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties1 = new NonVisualGraphicFrameDrawingProperties();
A.GraphicFrameLocks graphicFrameLocks1 = new A.GraphicFrameLocks() { NoChangeAspect = true };
graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
nonVisualGraphicFrameDrawingProperties1.Append(graphicFrameLocks1);
A.Graphic graphic1 = new A.Graphic();
graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
A.GraphicData graphicData1 = new A.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };
Pic.Picture picture1 = new Pic.Picture();
picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
Pic.NonVisualPictureProperties nonVisualPictureProperties1 = new Pic.NonVisualPictureProperties();
Pic.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Pic.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = "AddTo_Blink.png" };
Pic.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Pic.NonVisualPictureDrawingProperties();
nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
Pic.BlipFill blipFill1 = new Pic.BlipFill();
A.Blip blip1 = new A.Blip() { Embed = relationshipID };
A.BlipExtensionList blipExtensionList1 = new A.BlipExtensionList();
A.BlipExtension blipExtension1 = new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" };
A14.UseLocalDpi useLocalDpi1 = new A14.UseLocalDpi() { Val = false };
useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
blipExtension1.Append(useLocalDpi1);
blipExtensionList1.Append(blipExtension1);
blip1.Append(blipExtensionList1);
A.Stretch stretch1 = new A.Stretch();
A.FillRectangle fillRectangle1 = new A.FillRectangle();
stretch1.Append(fillRectangle1);
blipFill1.Append(blip1);
blipFill1.Append(stretch1);
Pic.ShapeProperties shapeProperties1 = new Pic.ShapeProperties();
A.Transform2D transform2D1 = new A.Transform2D();
A.Offset offset1 = new A.Offset() { X = 0L, Y = 0L };
A.Extents extents1 = new A.Extents() { Cx = 152400L, Cy = 152400L };
transform2D1.Append(offset1);
transform2D1.Append(extents1);
A.PresetGeometry presetGeometry1 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
presetGeometry1.Append(adjustValueList1);
shapeProperties1.Append(transform2D1);
shapeProperties1.Append(presetGeometry1);
picture1.Append(nonVisualPictureProperties1);
picture1.Append(blipFill1);
picture1.Append(shapeProperties1);
graphicData1.Append(picture1);
graphic1.Append(graphicData1);
inline1.Append(extent1);
inline1.Append(effectExtent1);
inline1.Append(docProperties1);
inline1.Append(nonVisualGraphicFrameDrawingProperties1);
inline1.Append(graphic1);
drawing1.Append(inline1);
return drawing1;
}
all images are shown at the end of body.
From the OXML SDK productivity tool I can see that bookmarks are used to insert images inside a paragraph.
To summarize, I want to know how to keep images when moving content controls from header to the body.
Regards.
When you add your image part to the mainPart, it will be given a relId which is unlikely to be the same as the relId it had in the headerPart. So you'll have to adjust the relId in the drawing (Embed = relationshipID) to match.
I'm able to successfully create a spreadsheet, and I appear to have added the image via code, the problem is that when I open the spreadsheet, there is no image. Here is my code:
public static void CreateSpreadsheetWorkbook(string filepath)
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
sheets.Append(sheet);
string sImagePath = #"C:\temp\install_button.png";
DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
ImagePart imagePart = drawingsPart.AddImagePart(ImagePartType.Png, worksheetPart.GetIdOfPart(drawingsPart));
using (FileStream stream = new FileStream(sImagePath, FileMode.Open))
{
imagePart.FeedData(stream);
}
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
}
Thanks
Stu
Normally when I can't figure out why something doesn't work when dealing with the Open XML SDK I use the Open XML SDK 2.0 Productivity Tool to figure out what the code should be. I will normally create a blank worksheet in Excel, add a picture and then save the document. Then I will open that document in the Productivity tool and click the Reflect code button to see how to recreate that document. I did that to see how to answer your question and got the following code to create a worksheet part:
// Adds child parts and generates content of the specified part.
public void CreateWorksheetPart(WorksheetPart part)
{
DrawingsPart drawingsPart1 = part.AddNewPart<DrawingsPart>("rId2");
GenerateDrawingsPart1Content(drawingsPart1);
ImagePart imagePart1 = drawingsPart1.AddNewPart<ImagePart>("image/png", "rId1");
GenerateImagePart1Content(imagePart1);
SpreadsheetPrinterSettingsPart spreadsheetPrinterSettingsPart1 = part.AddNewPart<SpreadsheetPrinterSettingsPart>("rId1");
GenerateSpreadsheetPrinterSettingsPart1Content(spreadsheetPrinterSettingsPart1);
GeneratePartContent(part);
}
// Generates content of drawingsPart1.
private void GenerateDrawingsPart1Content(DrawingsPart drawingsPart1)
{
Xdr.WorksheetDrawing worksheetDrawing1 = new Xdr.WorksheetDrawing();
worksheetDrawing1.AddNamespaceDeclaration("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");
worksheetDrawing1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
Xdr.TwoCellAnchor twoCellAnchor1 = new Xdr.TwoCellAnchor(){ EditAs = Xdr.EditAsValues.OneCell };
Xdr.FromMarker fromMarker1 = new Xdr.FromMarker();
Xdr.ColumnId columnId1 = new Xdr.ColumnId();
columnId1.Text = "0";
Xdr.ColumnOffset columnOffset1 = new Xdr.ColumnOffset();
columnOffset1.Text = "0";
Xdr.RowId rowId1 = new Xdr.RowId();
rowId1.Text = "0";
Xdr.RowOffset rowOffset1 = new Xdr.RowOffset();
rowOffset1.Text = "0";
fromMarker1.Append(columnId1);
fromMarker1.Append(columnOffset1);
fromMarker1.Append(rowId1);
fromMarker1.Append(rowOffset1);
Xdr.ToMarker toMarker1 = new Xdr.ToMarker();
Xdr.ColumnId columnId2 = new Xdr.ColumnId();
columnId2.Text = "0";
Xdr.ColumnOffset columnOffset2 = new Xdr.ColumnOffset();
columnOffset2.Text = "171429";
Xdr.RowId rowId2 = new Xdr.RowId();
rowId2.Text = "0";
Xdr.RowOffset rowOffset2 = new Xdr.RowOffset();
rowOffset2.Text = "171429";
toMarker1.Append(columnId2);
toMarker1.Append(columnOffset2);
toMarker1.Append(rowId2);
toMarker1.Append(rowOffset2);
Xdr.Picture picture1 = new Xdr.Picture();
Xdr.NonVisualPictureProperties nonVisualPictureProperties1 = new Xdr.NonVisualPictureProperties();
Xdr.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Xdr.NonVisualDrawingProperties(){ Id = (UInt32Value)2U, Name = "Picture 1", Description = "eprs_reports_arrow.png" };
Xdr.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Xdr.NonVisualPictureDrawingProperties();
A.PictureLocks pictureLocks1 = new A.PictureLocks(){ NoChangeAspect = true };
nonVisualPictureDrawingProperties1.Append(pictureLocks1);
nonVisualPictureProperties1.Append(nonVisualDrawingProperties1);
nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
Xdr.BlipFill blipFill1 = new Xdr.BlipFill();
A.Blip blip1 = new A.Blip(){ Embed = "rId1", CompressionState = A.BlipCompressionValues.Print };
blip1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
A.Stretch stretch1 = new A.Stretch();
A.FillRectangle fillRectangle1 = new A.FillRectangle();
stretch1.Append(fillRectangle1);
blipFill1.Append(blip1);
blipFill1.Append(stretch1);
Xdr.ShapeProperties shapeProperties1 = new Xdr.ShapeProperties();
A.Transform2D transform2D1 = new A.Transform2D();
A.Offset offset1 = new A.Offset(){ X = 0L, Y = 0L };
A.Extents extents1 = new A.Extents(){ Cx = 171429L, Cy = 171429L };
transform2D1.Append(offset1);
transform2D1.Append(extents1);
A.PresetGeometry presetGeometry1 = new A.PresetGeometry(){ Preset = A.ShapeTypeValues.Rectangle };
A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
presetGeometry1.Append(adjustValueList1);
shapeProperties1.Append(transform2D1);
shapeProperties1.Append(presetGeometry1);
picture1.Append(nonVisualPictureProperties1);
picture1.Append(blipFill1);
picture1.Append(shapeProperties1);
Xdr.ClientData clientData1 = new Xdr.ClientData();
twoCellAnchor1.Append(fromMarker1);
twoCellAnchor1.Append(toMarker1);
twoCellAnchor1.Append(picture1);
twoCellAnchor1.Append(clientData1);
worksheetDrawing1.Append(twoCellAnchor1);
drawingsPart1.WorksheetDrawing = worksheetDrawing1;
}
// Generates content of imagePart1.
private void GenerateImagePart1Content(ImagePart imagePart1)
{
System.IO.Stream data = GetBinaryDataStream(imagePart1Data);
imagePart1.FeedData(data);
data.Close();
}
// Generates content of spreadsheetPrinterSettingsPart1.
private void GenerateSpreadsheetPrinterSettingsPart1Content(SpreadsheetPrinterSettingsPart spreadsheetPrinterSettingsPart1)
{
System.IO.Stream data = GetBinaryDataStream(spreadsheetPrinterSettingsPart1Data);
spreadsheetPrinterSettingsPart1.FeedData(data);
data.Close();
}
// Generates content of part.
private void GeneratePartContent(WorksheetPart part)
{
Worksheet worksheet1 = new Worksheet();
worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension1 = new SheetDimension(){ Reference = "A1" };
SheetViews sheetViews1 = new SheetViews();
SheetView sheetView1 = new SheetView(){ TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews1.Append(sheetView1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties(){ DefaultRowHeight = 15D };
SheetData sheetData1 = new SheetData();
PageMargins pageMargins1 = new PageMargins(){ Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
PageSetup pageSetup1 = new PageSetup(){ Orientation = OrientationValues.Portrait, Id = "rId1" };
Drawing drawing1 = new Drawing(){ Id = "rId2" };
worksheet1.Append(sheetDimension1);
worksheet1.Append(sheetViews1);
worksheet1.Append(sheetFormatProperties1);
worksheet1.Append(sheetData1);
worksheet1.Append(pageMargins1);
worksheet1.Append(pageSetup1);
worksheet1.Append(drawing1);
part.Worksheet = worksheet1;
}
#region Binary Data
private string imagePart1Data ="lots of binary data here";
private System.IO.Stream GetBinaryDataStream(string base64String)
{
return new System.IO.MemoryStream(System.Convert.FromBase64String(base64String));
}
#endregion
I recommend you do the same with your image and play around with the generated code in order to get it to work since as you can see just adding one picture to a new slide is a lot of code.