Sketch Type On Path

Posted on by  admin

Dec 24, 2014  Quickly and easily create text on a path inside of Bohemian Coding's Sketch 3. This trick is still being de-bugged. The fastest cure is to flip the circle to place text.

  1. Sketch Text On Path Disappears
  2. Sketch Type On Path Line
  3. Sketch Highlight Text

A collection of recipes for Sketch App plugins developers.

I will be posting daily updates in my twitter. Follow me @turbobabr to stay tuned.

NOTE: All the samples are tested against Sketch 51

#20 Converting SVG Path Commands to Sketch Vector Shapes

In case you want to create a MSShapeGroup layer out of set of SVG Path Commands, there is an easy way to do that by using+SVGPathInterpreter.bezierPathFromCommands:(NSString*)commands isPathClosed:(char *)isClosed class method. I bet Sketch uses it internally to parse SVG files and convert them to vector shapes... let's give it a shot:

Note: Pay special attention to the required isPathClosed argument, that should be passed as pointer. You can read more about pointers in #18 Using Obj-C Pointers + Handling Cocoa Errors recipe.

#19 Inserting Emoji as Bitmap Layers

Frankly speaking, this recipe doesn't show any new tricks related to Sketch itself. I just want to demonstrate the power of AppKit/CoreGraphics frameworks and how they could be used in Sketch plugins.

No more words, here is the code:

Credits:

  • Idea and original code by Daniel Jalkut (Evergreen Images)
  • List of all emoji for JavaScript by @theraot (emoji)

#18 Using Obj-C Pointers + Handling Cocoa Errors

Many AppKit and Sketch internal APIs have methods and functions that require passing so called pointer to pointer arguments. Whenever you see argument type that looks like (id *), NSError **, NSError * _Nullable *, etc in any Objective-C API - it means that it wants pointer that points to a pointer thing :). It came to Objective-C from C Programming Language, since Objective-C is a layer build atop of C Language. You can read more about that pointer to pointer concept here - TurorialsPoint: C - Pointer to Pointer. Also, there's another case when we need to pass pointers to C value variables, e.g. (char*) to let method populate the value of that variable during it's execution.

Too bad that JavaScript language and engines don't support such thing as pointer at all, but we need them! Good news everyone! Sketch uses Mocha Framework for bridging Objective-C objects to JavaScript context and this framework has a special class to deal with pointers called MOPointer.

Using MOPointer class to call methods requiring pointer as one of arguments

Suppose we want to convert SVG Path Commands to NSBezierPath for further use in our plugin. Sketch has a handy class named SVGPathInterpreter and a super useful +SVGPathInterpreter.bezierPathFromCommands:(NSString*)commands isPathClosed:(char *)isClosed class method that takes a set of svg path commands as string and returns and instance of NSBezierPath representing the path defined by these commands.

But, there is a second argument named isPathClosed of (char *) type which is a pointer to a char(basically a single byte):

Let's try to pass null value just to call the method, we don't really care about whether path is closed or not, we just need to convert it to NSBezierPath instance:

Another attempt... let's feed an arbitrary variable to the method:

The correct way to call this method is to create MOPointer class instance and feed it to the method:

Dealing with NSErrors and handling errors in AppKit APIs

There are dozens of APIs both in Sketch and AppKit that throws various errors, usually errors handling is optional and we can omit it. For example, let's take +NSString.stringWithContentsOfFile:encoding:error: class method that can read text file to a string. In case this method fails to read file, it returns null as a result and indicates that something went wrong.

Just run the following code in custom script editor without any changes:

As you can see, it fails because the provided file isn't exist in your file system. It's not a big deal, since we receive null as a result and can check it making an assumption that null means that file isn't exist, but in reality the method might fail for a number of reasons like insufficient permissions, wrong encoding, etc.

In order to check for exact reason why it fails, we have to use MOPointer class again:

As you can see, by calling errorPtr.value(), we get an instance of NSError class describing the real reason why method failed:

Error Domain=NSCocoaErrorDomain Code=260 'The file “path.txt” couldn’t be opened because there is no such file.' UserInfo={NSFilePath=/some/non/existing/file/path.txt, NSUnderlyingError=0x60800204c600 {Error Domain=NSPOSIXErrorDomain Code=2 'No such file or directory'}}

Handling errors correctly might help a lot during development phase as well as make your plugin more stable. I strongly recommend to check out Dealing with Errors and Error Handling Programming Guide docs from Apple to get familiar with the way errors work and handled in Cocoa apps.

#17 Working with files

Author: @pravdomil

Save string to file.

More can be found in sskyy/blade repo.

#16 Using Image Fills

Sketch Text On Path Disappears

Sketch supports a bunch of various modes to fill style based layers(MSShapeGroup, MSTextLayer, etc) with images. Currently, we can use for modes that illustrated below:

To get started, we have to grab a couple of useful definitions of Sketch constants from sketch-constants repo. They will be used in all the examples below:

Using local image files

The following sample code demonstrates how to load image from the local file system and set it as a pattern fill for selected layer:

Using remote image files

In order to use remote image file we have to download it first and convert to an instance of NSImage first using a helper function:

Caution: Sketch does not support HTTP requests using plain http protocol due to App Transport Security (ATS) networking permissions defined in SketchApp. Be sure that you use https protocol and all your urls has https:// perfix.

Using tiled fill

There's a special case for Tile mode, since it has additional patternTileScale property involved to control scaling of the image pattern:

As a result of running the sample above, you might get something like this:

#15 Working with Constraints

All edge constraints are always anchored to a parent group (e.g, artboard, symbol or layer group) of the layer:

To control certain constraints, MSLayer class has a bunch of get/set properties named hasFixed[Edge/Size] that allow to get and update information about constraints for a given layer:

Checking current constraints:

Setting all edge constraints to fixed:

#14 CocoaScript: Don't use ' operator

At first glance CocoaScript seems to be a just fancy name for JavaScript with some syntactic sugar, but in reality many things work differently and it's better to know them.

One of the caveats are and ! operators best known as strict equality and strict not equal. The very brief suggestion about them is:

  • AVOID USING THEM AT ANY COST IN SKETCH PLUGINS!

To understand the problem, try to run the following script:

It will produce true for operator and false for . The string values are equal, both are assigned with 'hello!' string but their types are different. Now run this script to check their types:

As you can see, variables strA & strB are of different types. strA is a JavaScript string, but strB is a mysterious MOBoxedObject. The problem is in definition of strB - @'hello!' is equal to NSString.stringWithString('hello!') and it produces boxed instance of NSString class instead of JS string.

When developing Sketch plugins, you usually deal with the data that is produced on Sketch Runtime side. And most of the property getters and class methods return boxed Objective-C objects instead of native JS objects.

To demonstrate a real world problem you can easily encounter with: (1) Create a rectangle shape, (2) Select it, (3) Run the following script:

Note: The usage of and ! isn't forbidden, you can use them whenever you want to, but always pay attention to types of variables you compare. It's especially important when you try to port an existing JavaScript library or framework to CocoaScript. But anyway, I insist to forget strict equal/not equal operators and use ' and '!=' + manual type check if needed.

#13 Playing Sounds

Usually sounds bound to commands are annoying and useless, but sometimes they are very helpful when used with care.

Since Sketch plugins have access to all the APIs of AppKit Framework, we are able to do really crazy & cool things with plugins.. for example play a beep! sound when plugin shows an error message using -MSDocument.showMessage: method to make the message more noticeable to a user.

Here is how we can play beep sound to indicate some sort of error:

To play a custom audio file we can use a simple interface of NSSound class. Here is the sample code how to use it:

Alternatively, you can play any system sound using a handy +NSSound.soundNamed: class method:

#12 Centering Rectangle on Canvas

To center canvas on a certain point or region, you can use a handy -(void)MSContentDrawView.centerRect:(CGRect)rect animated:(BOOL)animated instance method, where rect is a rectangle to be centered, animated is a flag that turns on/off animation during the scrolling process.

The origin and size of the rectangle you provide to this method should be in absolute coordinates.

The following example centers viewport by x:200,y:200 point:

The example below shows how to center on the first selected layer using the same method without animation:

#11 Creating Custom Shapes

To create a custom vector shape programmatically, you have to create an instance of NSBezierPath class and draw whatever shape or combination of shapes you want to. Then convert the path to MSPath class instance and create a shape group out of it using +(MSShapeGroup*)MSShapeGroup.layerWithPath:(MSPath*)path class method.

This technique is very similar to creation of custom paths described in previous recipe. The only difference is that you have to close the path before converting it to the shape group.

The following example create a simple arrow shape:

#10 Creating Line Shapes

In order to create a line shape programmatically, you have to create an instance of NSBezierPath class and add two points to it. Then convert the path to MSPath class instance and create a shape group out of it using +(MSShapeGroup*)MSShapeGroup.layerWithPath:(MSPath*)path class method.

To make Sketch recognize the provided path as a line shape, you have to add only two points using moveToPoint & lineToPoint methods of NSBezierPath.

The following example creates a simple line shape with two points:

The same way, you can easily create a multi segment line using methods provided by NSBezierPath class. Whenever you add more than two points into the path, Sketch treats such shape as a vector path similar to what can be created using standard V - Vector tool.

The following example demonstrates how to create a curved path with four points:

#9 Setting Border Radius for Specific Corners

Starting from version 3.2 Sketch allows to set custom border radius for specific corner of rectangle shape. It was possible prior to 3.2, but there was no direct API.

In order to set custom radiuses you use -MSRectangleShape.setCornerRadiusFromComponents:(NSString*)compoents instance method, where components is a string that represents radius values for every corner separated by ; character. The sequence is following: top-left/top-right/bottom-right/bottom-left.

The following sample sets left-top and right-top corners of a selected rect shape to 15 points:

#8 Scaling Layers

You can scale any layer using -MSLayer.multiplyBy:(double)scaleFactor instance method, where scaleFactor is a floating-point value that is used to multiple all the layers' properties including position, size, and all the style attributes such as border thickness, shadow, etc. Here are some example scale factors: 1.0 = 100%, 2.5 = 250%, 0.5 = 50%, etc.

This method produces the same result as a standard Scale tool. Since all the layer type classes are inherited from MSLayer class, you can use this method to scale any type of layer including Pages and Artboards.

Note: After the call of the method, x and y position values will also be multiplied. If you need the layer to remain in the same position after scaling, you'll have to change its position to the appropriate values.

The following sample demonstrates how to scale first selected layer:

#7 Finding Bounds For a Set of Layers

If you want to quickly find a bounding rectangle for selected layers or any set of layers, there is a very handy class method for that +(CGRect)MSLayerGroup.groupBoundsForContainer:(MSLayerArray*)container. It accepts an instance of MSLayerArray class, that represents a list of layers.

Sketch Type On Path Line

A quick sample that demonstrate how to use it:

#6 Creating Oval Shapes

In order to create an oval shape programmatically, you have to create an instance of MSOvalShape class, set its frame and wrap with MSShapeGroup container.

The following sample demonstrates how to do it:

#5 Creating MSColor instances from CSS color strings (hex, rgba, etc)

There is no way to create instance of MSColor model class from CSS string directly, but it's possible to do so via it's immutable counterpart class named MSImmutableColor. It has a class method +MSImmutableColor.colorWithSVGString:(NSString*)string that accepts any value supported by CSS Color data type.

Here is a super handy helper function and a bunch of calls with various supported formats of providing color as string:

The following example demonstrates how to set fill color for a selected layer using MSColorFromString helper function:

#4 Flattening Complex Vector Layers

If you want to flatten a complex vector layer that contains several sub paths combined using different boolean operations into single layer, you can use +MSShapeGroup.flatten method.

This sample code flattens a first selected vector layer:

#3 Flattening Layers to Bitmap

In order to flatten one or several layers of any type to a single MSBitmapLayer, use -MSLayerFlattener.flattenLayers: method. It accepts one arguments which is a container of layers to be flattened.

The following example flattens all the selected layers to a bitmap layer:

#2 Converting Text Layer to Vector

In order to convert an existing MSTextLayer to MSShapeGroup layer, you have to get texts' NSBezierPath representation and then convert it to a MSShapeGroup layer.

The following source code demonstrates how to get text layers' vector outline and use it to create a vector shape from it:

#1 Getting Points Coordinates Along a Shape Path

If you want to distribute some shapes along a path there is a convenient method -pointOnPathAtLength: implemented in NSBezierPath_Slopes class extension.

This method accepts a double value that represents a position on path at which you want to get a point coordinate, where 0.0 value means start of the path and 1.0 end of the path. It returns a CGPoint struct with coordinates of the point.

The following example divides shape path into 15 segments and prints out their points coordinates:

Starting with the October 2018 Update, Windows 10 is modernizing the experience to take screenshots with the new Snip & Sketch app, which combines the legacy Snipping Tool with Screen sketch (previously part of Windows Ink Workspace).

Sketch Highlight Text

The result is a single experience to take and annotate screenshots of the desktop, apps, and games without the need for third-party tools, and an app that will be frequently updated through the Microsoft Store.

In this Windows 10 guide, we'll walk you through the steps to get started with the new Snip & Sketch app to take screenshots with the October 2018 update.

How to take screenshots with Snip & Sketch

Using Snip & Sketch, there are at least three ways to access and take screenshots on Windows 10:

Using Snip & Sketch app

The easiest way to get to the snipping tools is to use the Snip & Sketch app with these steps:

  1. Open Start.
  2. Search for Snip & Sketch, click the top result to open the experience.
  3. Click the New button in the top-left corner.

  4. Select the type of snip you want to use, including:

    • Rectangular Clip.
    • Freeform Clip.
    • Fullscreen Clip.
  5. Take the screenshot.

Using Action Center quick button

If you want to take a screenshot to paste on a document, you can use the new Screen snip button using these steps:

  1. Open Action Center.

    Quick tip: Use the Windows key + A keyboard shortcut, or click the Action Center button in the notification area to open the experience.

  2. Click the Expand button.
  3. Click the Screen snip button.

  4. Select the type of snip you want to use, including:

    • Rectangular Clip.
    • Freeform Clip.
    • Fullscreen Clip.
  5. Take the screenshot.

Using the Print Screen button

If you enabled the option, you can take screenshots on Windows 10 using the Print Screen key.

  1. Hit the Print Screen button.

    Quick Tip: Alternatively, you can use the Windows key + Shift + S shortcut to open the snipping toolbar.

  2. Select the type of snip you want to use, including:

    • Rectangular Clip.
    • Freeform Clip.
    • Fullscreen Clip.
  3. Take the screenshot.

Unlike using Snip & Sketch app when using the Screen snip button or the Print Screen key, the screenshot will copy to the clipboard. If you want to annotate the snip or save it into a file, you need to click the Snip & Sketch notifications in Action Center.

How to enable Print Screen button to use Snip & Sketch

You can also bring up the screen snipping tool using the Print Screen button on the keyboard, but it's an option that you need to enable manually using these steps:

  1. Open Settings.
  2. Click on Ease of Access.
  3. Click on Keyboard.
  4. Under 'Print Screen shortcut,' turn on the Use the PrtScn button to open the screen snipping option.

After completing the steps, you can hit the Print Screen key on your keyboard to take screenshots on Windows 10.

How to annotate screenshots with Snip & Sketch

Alongside the ability to quickly take screenshots on Windows 10, the app includes a number of tools to annotate images virtually any way you like.

Once you've taken the screenshot (or you can use the open (folder) button to load an image), the image will open in Snip & Sketch. While in the experience, you can use a number of tools to annotate the screenshot, including ballpoint pen, pencil, and marker. All of which you can click to customize the color and thickness.

In addition, there's an eraser to delete one or all the strokes from the screenshot. You can use the digital ruler to draw straight lines, and there's a cropping tool to trim the excess.

These tools have been designed to work best using a stylus on a touch-enabled device, but they also work with a keyboard and mouse.

Sketch type on path map

On the far-right corner, you'll find the options to save the snip as a PNG file. You can also use the copy button to copy the image to the clipboard, which you can then paste on any document.

Finally, there's the share button that brings up the experience to send the screenshot to another person using email, nearby sharing, or another supported application.

Do you like the new experience to take screenshots on Windows 10? Tell us in the comments.

More Windows 10 resources

For more helpful articles, coverage, and answers to common questions about Windows 10, visit the following resources:

Comments are closed.