How to snap-to-grid in macOS via Swift? - xcode

I'm developing simple app for macOS using Swift 2. How can I snap a CGPoint to grid (5-pixel distance for example) pressing a keyboard shortcut? I need such kind of point snapping as it's found in AutoCAD.
I am looking for a solution for final project not Interface Builder.

this is the general way to do it, something like a pseudo code
var gridWidth = 16.0
var gridHeight = 16.0
object.Position.X = Math.Floor(object.Position.X / gridWidth) * gridWidth
object.Position.Y = Math.Floor(object.Position.Y / gridHeight) * gridHeight

Related

CocosSharp game on Android startup takes a long time to draw graphics

We have a somewhat simple game written using CocosSharp. The game is within another Xamarin.Forms app. When the player clicks to play the game, we bring them to a splash screen. On iOS this screen displays immediately but on Android, the screen is just black for about 15 seconds. The music plays pretty much immediately on both platforms.
The following is called from the ViewCreated event of the CocosSharpView.
InitializeAudio();
var scene = new Scenes.SplashScene(GameView);
GameView.RunWithScene(scene);
The hang up seems to be when creating labels. The following take ~10 seconds to complete with 99% of it being in the constructor of the first label. We call our CreateText in the constructor.
private void CreateText()
{
var label = new CCLabel("Text 1", "BD_CARTOON_SHOUT.TTF", 80)
{
PositionX = layer.ContentSize.Width / 2.0f,
PositionY = layer.ContentSize.Height / 1.5f,
Color = CCColor3B.DarkGray
};
layer.AddChild(label);
label = new CCLabel("Text 2", "BD_CARTOON_SHOUT.TTF", 60)
{
PositionX = layer.ContentSize.Width / 2.0f,
PositionY = 50f,
Color = CCColor3B.DarkGray
};
layer.AddChild(label);
}
Keep in mind this only happens on Android.
Thanks in advance!
I had the same issue several weeks ago. The problem was CCLabel constructor
where it didn't know which type of font are you using and therefore trying all other types before finally trying the last one which is correct. You need to specify font type in CCLabel constructor like this:
var label = new CCLabel("Text 1", "BD_CARTOON_SHOUT.TTF", 80, CCLabelFormat.SystemFont);
Hope it helps.

How can I create a label text with shadow?

I'm trying to create a label text with a shadow created automatically by the system. In iOS I know that you can use an Attributed style for the label, but in OS X I can't find this option. Could you help?
You can do that with Core Animation (a.k.a. CALayer). Views in iOS are layer-backed by default, but NSView on Mac OS X are much older and requires you to turn on layer manually.
The easiest way is to go to the View Effects Inspector (Cmd + Alt + 8):
If you want to add the shadow programmatically:
override func awakeFromNib() {
let shadow = NSShadow()
shadow.shadowOffset = NSMakeSize(5,5)
shadow.shadowBlurRadius = 5
shadow.shadowColor = NSColor.blackColor()
myLabel.superview?.wantsLayer = true
myLabel.shadow = shadow
}

Firefox Addon API for Taking Screenshot

I am looking for firefox addon api to take screenshot of visible area of document.
Chrome and Safari have api's to achieve this. And they are pretty fast.
I could not find anything specific for firefox.
I found a workaround at How do I use the canvas drawWindow function in an addon created using the addon sdk? but this solution takes full page screenshot with scrolls including (hidden parts of document). There are 2 issues for this solution;
1- if page has long scroll, it takes long time to complete screenshot process. Because it is using canvas based drawing.
2- I would like to get screenshot of visible area of document, not whole document.
Is there any workaround for this?
Thanks.
Using the SDK you can do something like this:
const { window: { document } } = require('sdk/addon/window');
const { getTabContentWindow, getActiveTab } = require('sdk/tabs/utils');
const { getMostRecentBrowserWindow } = require('sdk/window/utils');
const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
document.documentElement.appendChild(canvas);
function captureTab(tab=getActiveTab(getMostRecentBrowserWindow())) {
let contentWindow = getTabContentWindow(tab);
let w = contentWindow.innerWidth;
let h = contentWindow.innerHeight;
let x = contentWindow.scrollX;
let y = contentWindow.scrollY;
canvas.width = w;
canvas.height = h;
let ctx = canvas.getContext('2d');
ctx.drawWindow(contentWindow, x, y, w, h, '#000');
return canvas.toDataURL();
}
That should takes only the visible area. By default, it grabs the active tab, but you can pass any other tab – because is designed as low level API it takes a native tab, however, not a SDK tab.
You can put in a module and exports just the captureTab function.
Edit: e10s version
The code above is not currently compatible with Firefox with e10s available, as Ian Bicking noted in the comment. An easy way to workaround this issue, is create a temporary canvas in the same document and content process we want to capture the screenshot:
const { getTabContentWindow, getActiveTab } = require('sdk/tabs/utils');
const { getMostRecentBrowserWindow } = require('sdk/window/utils');
function captureTab(tab=getActiveTab(getMostRecentBrowserWindow())) {
let contentWindow = getTabContentWindow(tab);
let { document } = contentWindow;
let w = contentWindow.innerWidth;
let h = contentWindow.innerHeight;
let x = contentWindow.scrollX;
let y = contentWindow.scrollY;
let canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
canvas.width = w;
canvas.height = h;
let ctx = canvas.getContext('2d');
ctx.drawWindow(contentWindow, x, y, w, h, '#000');
let dataURL = canvas.toDataURL();
canvas = null;
return dataURL;
}
That works in both e10s and no-e10s FF version; the downside comparing to the previous one is creating a canvas every time we want to take a screenshot, but I think is acceptable.
Your assumption that taking a screenshot on Firefox with canvas is somehow slow is wrong.
I did a couple of screenshots and Firefox/canvas was faster than Chrome/captureVisibleTab.
Actually Firefox is better suited for as-fast-as-possible screenshots, since its canvas expose to privileged code the mozFetchAsStream method, allowing to bypass the actual bottleneck which is the base64 encoding of the image data.
Some numbers
Chrome: captureVisibleTab 200-205ms
Firefox: drawImage 20-25ms + toDataURL 125-130ms
The devtools screenshot command is a good example of how to capture just the visible part
In all fairness, to make a meaningful comparison one has to take into account whether Chrome's PNG encoder favors compression over speed. Still, this doesn't change the fact that Firefox's canvas is fine.
edit: OK, that base64 encoding remark is dumb, I don't know what I was thinking. Perhaps what I should write instead is that Firefox's canvas is not only fast but also versatile.

GPS accuracy Issues

I am developing a windows phone sports tracker app, that uses gps sensors to calculate the distance travelled by the runner, I am using geocoordinatewatcher class for the same, setting the movement threshold to 100. But, I find my app giving distance values even when the device is kept stationary. My app should give distance only when the device changes its position. I found the same bug in othere apps that are on the marketplace, please tell me where am I doing wrong?
My Code.
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
watcher.MovementThreshold = 150;
watcher.PositionChanged += watcher_PositionChanged;
watcher.Start();
{
latitudeCurrent = e.Position.Location.Latitude;
longitudeCurrent = e.Position.Location.Longitude;
if (stepCounter == 0)
{
latitudePrevious = latitudeCurrent;
longitudePrevious = longitudeCurrent;
distanceTravelled += Math.Round(Calculate(latitudePrevious,longitudePrevious,latitudeCurrent,longitudeCurrent),2);
txbDistanceTravelled.Text = distanceTravelled.ToString();
txbCalories.Text=string.Format("{0:f0}", distanceTravelled * 65);
stepCounter++;
var millisPerKilometer = (distanceTravelled) * (System.Environment.TickCount - _previousPositionChangeTick);
txbPace.Text = TimeSpan.FromMilliseconds(millisPerKilometer).ToString(#"mm\:ss");
double hrs = counterTick / 3600;
if (!double.IsNaN((distanceTravelled / hrs)))
{
txbSpeed.Text = (distanceTravelled / hrs).ToString();
}
else
{
txbSpeed.Text = "0";
}
}
}
You are developing your app for Windows Phone 7 or Windows Phone 8? IF you are developing for the later, you need to use the new Geolocator class and not GeoCoordinateWatcher.
Also, as LewisBenge said, if you are testing This indoor you can get WiFi positions or even cellular data. It could be better to test outdoor.
Your GPS signal might be weak in the place where you are testing. Try it in the outdoor location.

Is that possible to have a sliding panel?

I am developing an application in wp7, the application is already been developed in android and iPhone.
Both uses a component sliding panel as they are default in it, now for the same appearance am supposed to use the component gives the same look and feel.
Is that possible to use any combination of components OR any customized dll available for that component OR is there any alternated equivalent component available for this sliding pannel.
The sliding panel i expect is like this Video
My idea is very simple, just use popup with custom animation.
DoubleAnimation anima = new DoubleAnimation();
anima.From = //current position;
anima.To = //slider position;
//animation now proportional to pixel difference
anima.Duration = new Duration(System.TimeSpan.FromMilliseconds(Math.Abs((300))));
//Debug.WriteLine("Duration=" + TimeSpan.FromMilliseconds(Math.Abs((to - from) * 2)));
// Set attached properties
Storyboard.SetTarget(anima, m_Popup);
//Storyboard.SetTargetProperty(anima, new PropertyPath(System.Windows.Controls.Primitives.Popup.WidthProperty));
Storyboard.SetTargetProperty(anima, new PropertyPath(System.Windows.Controls.Primitives.Popup.VerticalOffsetProperty));
// Create storyboard, add animation, and fire it up!
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(anima);
storyboard.Begin();

Resources