Using scalabe svg files in Xamarin with the svg plugin - svg

I'm trying to use Xamarin Forms plugin SVG.Forms.Plugin.Abstractions to render scalable SVG files rather than create a file for each device size.
On reading the how-to, it states that to create the image in code I should do this:
new SvgImage
{
SvgPath = "pic.svg",
SvgAssembly = typeof (App).GetTypeInfo().Assembly,
HeightRequest = 200,
WidthRequest = 200,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.End,
BackgroundColor = Color.White
};
However I would rather do this in XAML, and so far have the following
<abstractions:SvgImage Grid.Row="1" Grid.Column="0" SvgAssembly="{Binding SvgAssembly}" SvgPath="{Binding SvgPath}" HeightRequest="250" WidthRequest="250" BackgroundColor="White" HorizontalOptions="Center" VerticalOptions="End"/>
I assume I need to bind SvgPath to a string value in the code behind, but I'm not sure what to bind the SvgAssembly to, I tried a string but it gave an unhandled runtime error.
Does anyone know how to do this?
thanks in advance

You should bind it to an actual assembly.
To simplify, you could just get the assembly from a type that is within the assembly you are looking:
Assembly SvgAssembly = typeof(ClassInAssembly).Assembly;
You should be good to go with this.
If you need to dig a bit deeper, check out my blog post about drawing SVG with SkiaSharp.

Related

Does default Zxing.Net.Mobile overlay contain a flash/torch button?

I am using the Zxing.Net.Mobile package within my Windows 10 universal app. I use the Default overlay, which is quite nice in my eyes. Now I want to add Flash/Torch funtionality to my application. I only found Solutions defining a new customn overlay. Is it not possible to activate a Torch button in the default overlay? I found a scanner.FlashButtonText Definition, so i think a flashbutton should somehow be activatable and i just dont know the Name of this Parameter. Can someone help me with this? Thanks.
my Code Looks like this:
var options = new MobileBarcodeScanningOptions
{
AutoRotate = false,
TryHarder = true,
PossibleFormats = new List<ZXing.BarcodeFormat>
{
ZXing.BarcodeFormat.EAN_8, ZXing.BarcodeFormat.EAN_13, ZXing.BarcodeFormat.UPC_A, ZXing.BarcodeFormat.UPC_E
}
};
var scanner = new MobileBarcodeScanner(this.Dispatcher);
scanner.UseCustomOverlay = false;
scanner.RootFrame = MyFrame;
scanner.TopText = "Halte die Kamera vor den Barcode";
scanner.BottomText = "Die Kamera scannt den Barcode automatisch";
scanner.FlashButtonText = "activate Torch";
var result = await scanner.Scan(options);
Although MobileBarcodeScanner has a FlashButtonText property, but according to ZXing.Net.Mobile's source code, Flash/Torch function is not supported in the default overlay by now.
The default overlay is set by ZXingScannerControl and if we look at its source code, we will find it does have a button named "buttonToggleFlash". However this button is invisible and there is no property can control its visibility.
source code:
<Border Grid.Row="0" Visibility="Collapsed" VerticalAlignment="Top" HorizontalAlignment="Right" Width="120" Height="80">
<Button x:Name="buttonToggleFlash" Click="buttonToggleFlash_Click">Flash</Button>
</Border>
So to support Flash/Torch function, you need a customn overlay. Or you can edit the source code and rebuild ZXing.Net.Mobile for your purpose.

Integrating Poilu raphael boolean operations(union,substraction) with SVG-edit

I am doing a modification of svg-edit, more specifically Mark McKays Method draw: https://github.com/duopixel/Method-Draw.
I want to use this Raphael library i found: https://github.com/poilu/raphael-boolean that allows me to perform boolean(set) operations on paths within my canvas.
Now i have implemented a button within the editor that fires up a function:
var paper = Raphael("canvas", 250, 250);
var path = paper.path("M 43,53 183,85 C 194,113 179,136 167,161 122,159 98,195 70,188 z");
path.attr({fill: "#a00", stroke: "none"});
var ellipse = paper.ellipse(170, 160, 40, 35);
ellipse.attr({fill: "#0a0", stroke: "none"});
var newPathStr = paper.union(path, ellipse);
//draw a new path element using that string
var newPath = paper.path(newPathStr);
newPath.attr({fill: "#666"});
// as they aren't needed anymore remove the other elements
path.remove();
ellipse.remove();
Okay, upon clicking the button isnt the editor supposed to return a unioned(welded) path with an ellipse?
or am i getting this wrong?
i am figuring that something must change with the var paper = Raphael("canvas", 250, 250); line since svg-edit is using a different name for the canvas but i have no idea how to go about it.
Any help will be deeply appreciated as i have been struggling for sometime with this.
UPDATE: This library is unable to handle multi-object welding, self intersections and many other cases. It is only working if we want to perform operations on 2 simple objects. This might not be immediately relevant to the question at hand but i thought it is wise to mention it anyway.
Refer to this question if you are looking for Boolean Operations on SVG elements: Boolean Operations on SVG paths
The code you posted works in isolation, as shown here: http://jsfiddle.net/5SaR3/
You should be able to change the Raphael constructor line to something like:
var paper = Raphael(canvas);
where canvas is an object reference to the SVG element used by svg-edit.

How to create a `pixelized' SVG image from a bitmap?

I have a 16x16 bitmap and want to create an SVG that contains 16x16 squares with the colors of the pixels of the image. Is there an easy way to achieve this?
My current thoughts go into the direction of using Python and PIL to read the bitmap image and dynamically create an SVG image file with the corresponding objects. But this feels a little clumsy and like reinventing the wheel.
Is there a better way to do this?
If you don't need the output to be SVG, I would suggest using an HTML5 Canvas where you can sample the pixels of the image client-side (using getImageData() on the context) and then draw your own up-scaled image. Or, if you need SVG, you could still use Canvas for the image sampling and then use procedurally-created <rect/> elements in SVG for each pixel.
I've written an example using just HTML Canvas so you can see how to do this. In short:
function drawPixelated(img,context,zoom,x,y){
if (!zoom) zoom=4; if (!x) x=0; if (!y) y=0;
if (!img.id) img.id = "__img"+(drawPixelated.lastImageId++);
var idata = drawPixelated.idataById[img.id];
if (!idata){
var ctx = document.createElement('canvas').getContext('2d');
ctx.width = img.width;
ctx.height = img.height;
ctx.drawImage(img,0,0);
idata = drawPixelated.idataById[img.id] = ctx.getImageData(0,0,img.width,img.height).data;
}
for (var x2=0;x2<img.width;++x2){
for (var y2=0;y2<img.height;++y2){
var i=(y2*img.width+x2)*4;
var r=idata[i ];
var g=idata[i+1];
var b=idata[i+2];
var a=idata[i+3];
context.fillStyle = "rgba("+r+","+g+","+b+","+(a/255)+")";
context.fillRect(x+x2*zoom, y+y2*zoom, zoom, zoom);
}
}
};
drawPixelated.idataById={};
drawPixelated.lastImageId=0;
If you really need SVG involved, I'd be happy to write an example that dynamically generated that.
Edit: OK, I've created an SVG version just for fun and practice. :)
As an aside (from an initial misreading of your question) this demo file from ASVG3 their old SVG Examples Page shows how to use some complex compositing of many different effects to create pixelation on arbitrary vector data. Unfortunately the demo does not load in Chrome, having been hardwired to require the (now-discontinued) Adobe SVG Viewer.

setIcon in j2me to set icons for buttons

I am trying to put in an icon (a scaled image) as part of a button that also contains some text. I am programming in J2ME for the Nokia SDK (S60 device) and using Eclipse.
The code is as follows:
but = new Button("Some text");
Image img = null;
try {
img = Image.createImage("/flower.png");
} catch(IOException e) {
e1.printStackTrace();
}
but.setIcon(img);
The above lines are the code that works properly. I am facing problems in scaling the image to the size of the button. Whenever I try to do that, I get a divide by zero error. The function I am using to scale the image and the way it is being scaled is:
Image img2 = null;
img2 = img.scaled(but.getWidth()/2, but.getHeight());
but.setIcon(img2);
I am unable to figure out why I get a divide by zero error every time I try to run the above code. Is there some other function that I should use? Or is there something I am missing ?
which UI Framework are using, is it LWUIT? if yes, you can't get the width/height of any component before showing the form, you should use getPreferredWidth instead

SVG Word Wrap - Show stopper?

For fun I am trying to see how far I can get at implementing an SVG browser client for a RIA I'm messing around with in my spare time.
But have hit what appears to be a HUGE stumbling block. There is no word wrap!!
Does anyone know of any work around (I'm thinking some kind of JavaScript or special tag I don't know)?
If not I'm either going to have to go the xhtml route and start sticking HTML elements in my SVG (ouch), or just come back again in ten years when SVG 1.2 is ready.
This SVG stuff is baffling, isn't it ?
Thankfully, you can achieve some good results, but it takes more work than using the HTML 5 .
Here's a screenshot of my ASP.Net / SVG app, featuring a bit of "faked" word wrapping.
The following function will create an SVG text element for you, broken into tspan pieces, where each line is no longer than 20 characters in length.
<text x="600" y="400" font-size="12" fill="#FFFFFF" text-anchor="middle">
<tspan x="600" y="400">Here a realy long </tspan>
<tspan x="600" y="416">title which needs </tspan>
<tspan x="600" y="432">wrapping </tspan>
</text>
It's not perfect, but it's simple, fast, and the users will never know the difference.
My createSVGtext() JavaScript function takes three parameters: an x-position, y-position and the text to be displayed. The font, maximum-chars-per-line and text color are all hardcoded in my function, but this can be easily changed.
To display the right-hand label shown in the screenshot above, you would call the function using:
var svgText = createSVGtext("Here a realy long title which needs wrapping", 600, 400);
$('svg').append(svgText);
And here's the JavaScript function:
function createSVGtext(caption, x, y) {
// This function attempts to create a new svg "text" element, chopping
// it up into "tspan" pieces, if the caption is too long
//
var svgText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
svgText.setAttributeNS(null, 'x', x);
svgText.setAttributeNS(null, 'y', y);
svgText.setAttributeNS(null, 'font-size', 12);
svgText.setAttributeNS(null, 'fill', '#FFFFFF'); // White text
svgText.setAttributeNS(null, 'text-anchor', 'middle'); // Center the text
// The following two variables should really be passed as parameters
var MAXIMUM_CHARS_PER_LINE = 20;
var LINE_HEIGHT = 16;
var words = caption.split(" ");
var line = "";
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + " ";
if (testLine.length > MAXIMUM_CHARS_PER_LINE)
{
// Add a new <tspan> element
var svgTSpan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
svgTSpan.setAttributeNS(null, 'x', x);
svgTSpan.setAttributeNS(null, 'y', y);
var tSpanTextNode = document.createTextNode(line);
svgTSpan.appendChild(tSpanTextNode);
svgText.appendChild(svgTSpan);
line = words[n] + " ";
y += LINE_HEIGHT;
}
else {
line = testLine;
}
}
var svgTSpan = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
svgTSpan.setAttributeNS(null, 'x', x);
svgTSpan.setAttributeNS(null, 'y', y);
var tSpanTextNode = document.createTextNode(line);
svgTSpan.appendChild(tSpanTextNode);
svgText.appendChild(svgTSpan);
return svgText;
}
The logic for word-wrapping is based on this HTML5 Canvas tutorial
I hope you find this useful !
Mike
http://www.MikesKnowledgeBase.com
UPDATE
One thing I forgot to mention.
That "Workflow diagram" screen that I've shown above was originally just written using an HTML 5 canvas. It worked beautifully, the icons could be dragged, popup menus could appear when you clicked on them, and even IE8 seemed happy with it.
But I found that if the diagram became "too big" (eg 4000 x 4000 pixels), then the would fail to initialise in all browsers, nothing would appear - but - as far as the JavaScript code was concerned, everything was working fine.
So, even with error-checking, my diagram was appearing blank, and I was unable to detect when this showstopper problem was occurring.
var canvasSupported = !!c.getContext;
if (!canvasSupported) {
// The user's browser doesn't support HTML 5 <Canvas> controls.
prompt("Workflow", "Your browser doesn't support drawing on HTML 5 canvases.");
return;
}
var context = c.getContext("2d");
if (context == null) {
// The user's browser doesn't support HTML 5 <Canvas> controls.
prompt("Workflow", "The canvas isn't drawable.");
return;
}
// With larger diagrams, the error-checking above failed to notice that
// the canvas wasn't being drawn.
So, this is why I've had to rewrite the JavaScript code to use SVG instead. It just seems to cope better with larger diagrams.
There is also foreignObject tag. Then you can embed HTML in SVG which gives the greatest flexibility. HTML is great for document layout and has been hacked to no end to support application layout, drawing, and everything us developers want. But it's strength is word wrapping and document layout. Let HTML do what it does best, and let SVG do what it does best.
http://www.w3.org/TR/SVG/extend.html
This works for most browsers FireFox, Opera, Webkit, except IE (as of IE11). :-( Story of the web ain't it?
SVGT 1.2 introduces the textArea element http://www.w3.org/TR/SVGTiny12/text.html#TextInAnArea , but it is only experimentally supported by Opera 10 at the moment. I don't know if other browsers will ever plan on implementing it, though I hope they will.
Per this document, it appears that tspan can give the illusion of word wrap:
The tspan tag is identical to the text tag but can be nested inside text tags and inside itself. Coupled with the 'dy' attribute this allows the illusion of word wrap in SVG 1.1. Note that 'dy' is relative to the last glyph (character) drawn.
The svg.js library has a svg.textflow.js plugin. It's not ultra fast but it does the trick. It even stores overflowing text in a data attribute so you can use it to create continuously flowing columns. Here the text flow example page.
An alternative method is to use Andreas Neuman's text box object.
These days, flowPara can do word wrapping, but I have yet to find a browser that supports it properly.
I've been looking for a solution about word wrapping in svg so many hours (or many days).
If you can in your app, edit your code to put some tspan, or any other method, go in it.
Text wrapping will be implement in the 1.2 version but except opera, no browser fully implement it yet (4 years, the specification are on the W3 ...).
Because I had to use some alignment settings, i couldn't use any of the code that many forum can provide (no foreign object, no carto script or anything).
If I post this message, it's just in order to be usefull to some other people when googling word wrapping svg because this post on the top result and in many case, this post doesn't help.
Here is a cool, easy and light solution :
http://dev.w3.org/SVG/profiles/1.1F2/test/svg/text-dom-01-f.svg

Resources