Best way to create a drawing app which can use images as fill - swift

I'm trying to create a section of an app where the user can draw freestyle shapes and fill these shapes with an image.
I have tried using UIBezierPaths and CAShapeLayers, and have been able to create a drawing app which fills all images with a single colour.
I want each shape to be able to be filled with a different colour, so eventually the individual shapes can be filled with separate images.
I'm having trouble separating each drawing so they can be filled individually, and have so far been unable to fill a drawing with an image.
If anyone has suggestions of other ways I could go about doing this, I would appreciate any ideas!

Have you thought about maybe using SpriteKit for the drawing portion of your app? Using Spritekit you can create your shapes using SKShapeNode and fill them with different colors using the fillColor property of SKShapeNode. For filling the newly create shape with an image you can place your image in an SKSpriteNode then crop it using SKCropNode and set the maskNode property of SKCropNode to the SKShapeNode you created.
Eample:
import UIKit
import SpriteKit
class DrawView: SKScene {
override func didMoveToView(view: SKView) {
scaleMode = .ResizeFill
backgroundColor = UIColor.whiteColor()
//creating a triangle and filling it with the color blue
let path = CGPathCreateMutable()
CGPathAddArc(path, nil, 160, 284, 0, 0, CGFloat(M_PI*2), true)
CGPathAddLineToPoint(path, nill, 60, 184)
CGPathAddLineToPoint(path, nill, 260, 184)
CGPathAddLineToPoint(path, nill, 60, 284)
let triangle = SKShapeNode()
triangle.lineCap = .Round
triangle.lineJoin = .Round
triangle.fillColor = UIColor.blueColor()
triangle.path = path
addChild(triangle)
//placing image into SKSpriteNode
let image = SKSpriteNode(imageNamed: "yourImage")
image.size = CGSizeMake(320, 568)
image.position = CGPointMake(160, 284)
//creating an SKCropNode
let imageCrop = SKCropNode()
imageCrop.position = CGPointMake(0, 0)
imageCrop.addChild(image) //adding image to the SKCropNode
imageCrop.maskNode = triangle //using the triangle created as a mask
addChild(imageCrop)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
//create spritekit scene
let skView = SKView(frame: CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height))
skView.center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2)
self.view.addSubview(skView)
//add drawing view to the scene
let drawView = DrawView()
sKView.presentScene(drawView)
}
}
The tricky part is going to be repositioning the SKSpriteNode and SKCropNode to fill the SKShapeNode.

Related

Draw a circular SKSpriteNode with texture?

Is there a way to draw a circular SKSpriteNode with texture? Or alternatively, draw a SKShapeNode with texture?
It is to consider that all images are rectangle/squares. What we see as round, is how we show colored pixels: what is outside the circle, is transparent and what is inside, is the colored part.
we need a circle
we texture it
we add it to the scene
we take back a new texture from this shape node that we just added to the scene
we make a new sprite using this new texture
we add the sprite to the scene
let shape: SKShapeNode = SKShapeNode(circleOfRadius: 50)
shape.name = "shape"
shape.lineWidth = 1 // this way we see that this is a circle
shape.fillColor = .white // to see the true colors of our image
//shape.strokeColor = .white
//shape.glowWidth = 0
shape.fillTexture = SKTexture(imageNamed:"myImage")
shape.position = CGPoint(x: 0, y:200)
self.addChild(shape)
let newTexture: SKTexture = (self.view?.texture(from: self.childNode(withName: "shape")!))!
let sprite: SKSpriteNode = SKSpriteNode(texture: newTexture)
self.addChild(sprite)
shape.removeFromParent()

Using an UIView as a Mask in another UIView on Swift

I am developing an App on xCode with Swift. My screen has an Image of an animal (outlet "backImage"), over this image I have a view (outlet "coverView"), color black, which covers all the screen. So so far you can't see the animal image, because the "coverView" is in front of it. Then I have another view (outlet "maskView") which is smaller and it's over the big view "coverView". What I want is to use this "maskView" as mask and therefor see the "backImage" through it, like a window.
Is there anyone out there able to figure this out?
Here is my screen, I want to see the woman character behind the big gray view through the smaller white view:
You can set the alpha property from your mask view and add in front of the other view, for instance:
let maskView = UIView()
maskView.backgroundColor = UIColor(white: 0, alpha: 0.5) //you can modify this to whatever you need
maskView.frame = CGRect(x: 0, y: 0, width: imageView.frame.width, height: imageView.frame.height)
yourView.addSubview(maskView)
EDIT: Now that you edited your question with an image, now I see what you need, so here is how you can accomplish that.
func setMask(with hole: CGRect, in view: UIView){
// Create a mutable path and add a rectangle that will be h
let mutablePath = CGMutablePath()
mutablePath.addRect(view.bounds)
mutablePath.addRect(hole)
// Create a shape layer and cut out the intersection
let mask = CAShapeLayer()
mask.path = mutablePath
mask.fillRule = kCAFillRuleEvenOdd
// Add the mask to the view
view.layer.mask = mask
}
With this function, all you need is to have a view and create a shape that it's going to be a hole in that view, for instance:
// Create the view (you can also use a view created in the storyboard)
let newView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
newView.backgroundColor = UIColor(white: 0, alpha: 1)
// You can play with these values and find one that fills your need
let rectangularHole = CGRect(x: view.bounds.width*0.3, y: view.bounds.height*0.3, width: view.bounds.width*0.5, height: view.bounds.height*0.5)
// Set the mask in the created view
setMask(with: rectangularHole, in: newView)
Thank you, #Alexandre Lara! You did it!
Here goes the solution:
#IBOutlet weak var windowView: UIView!
#IBOutlet weak var bigCoverView: UIView!
func setMask(with hole: CGRect, in view: UIView){
// Create a mutable path and add a rectangle that will be h
let mutablePath = CGMutablePath()
mutablePath.addRect(view.bounds)
mutablePath.addRect(hole)
// Create a shape layer and cut out the intersection
let mask = CAShapeLayer()
mask.path = mutablePath
mask.fillRule = kCAFillRuleEvenOdd
// Add the mask to the view
view.layer.mask = mask
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rectangularHole = windowView.frame.integral
// Set the mask in the created view
setMask(with: rectangularHole, in: bigCoverView!)
}

Rotate a SKShapeNode with texture

I'm trying to rotate an SKShapeNode with a texture, but it's not working. Basically, I have a circle with a texture and I'm trying to make it rotate using the same way I have done with an SKSpriteNode:
let spin = SKAction.rotateByAngle(CGFloat(M_PI/4.0), duration: 1)
The problem is that the circle is rotating, but not the texture. I can check this by using this code:
let wait = SKAction.waitForDuration(0.5)
let block = SKAction.runBlock({
print(self.circle.zRotation)
})
let sequence = SKAction.sequence([wait, block])
self.runAction(SKAction.repeatActionForever(sequence))
This is the code I have for creating the SKShapeNode:
let tex:SKTexture = SKTexture(image: image)
let circle = SKShapeNode(circleOfRadius: 100 )
circle.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + 200)
circle.strokeColor = SKColor.clearColor()
circle.glowWidth = 1.0
circle.fillColor = SKColor.whiteColor()
circle.fillTexture = tex
self.addChild(circle)
// Runing the action
circle.runAction(spin)
Please help. Thanks in advance!
PS: I know that using an SKSpriteNode would be better but my goal is to place a square image in a circular frame and I figured that using an SKShapeNode would be perfect. If anyone know how to create a circular SKSpriteNode, feel free to post it in the answers section! :)
This is what I'm trying to achieve (with the capability of rotating it):
You can achieve what you want by using SKCropNode and setting its mask property to be a circle texture:
override func didMoveToView(view: SKView) {
let maskShapeTexture = SKTexture(imageNamed: "circle")
let texture = SKTexture(imageNamed: "pictureToMask")
let pictureToMask = SKSpriteNode(texture: texture, size: texture.size())
let mask = SKSpriteNode(texture: maskShapeTexture) //make a circular mask
let cropNode = SKCropNode()
cropNode.maskNode = mask
cropNode.addChild(pictureToMask)
cropNode.position = CGPoint(x: frame.midX, y: frame.midY)
addChild(cropNode)
}
Let's say that picture to mask has a size of 300x300 pixels. The circle you are using as a mask, in that case, has to have the same size. Means the circle itself has to have a radius of 150 pixels (diameter of 300 pixels) when made in image editor.
Mask node determines the visible area of a picture. So don't make it too large. Mask node has to be a fully opaque circle with transparent background.

Draw a hole in a rectangle with SpriteKit?

How to draw a hole in a rectangle?
I want to draw a rectangle which has a empty hole inside it and the background can be show.
I am using SKShapeNode to create a rectangle, but I have no idea how to make a hole (circle) inside it.
This is what I run your code, but my circle is not empty, the circle is black, I want it to be empty.
Is there any mistake I didn't mention?
Here's the code.
import SpriteKit
class GameScene: SKScene {
override func didMove(to view: SKView) {
let effect = SKEffectNode()
addChild(effect)
let rect = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 400, height: 200))
rect.fillColor = .green
effect.addChild(rect)
let hole = SKShapeNode(circleOfRadius: 40)
hole.position = CGPoint(x: 200, y: 100)
hole.fillColor = .white
hole.blendMode = .subtract
rect.addChild(hole)
}
}
As you can see I create an SKEffectNode. Then I add to it the rectangle. Finally I add the hole to the rectangle.

Swift - How to create a view with a shape cropped in it

I'm trying to achieve the result shown in the image using swift 1.2 and xcode 6.
Basically I want to create a view with a shape cut in it to be able to see the the view below to make a tutorial for my app.
I know how to create a circular shape but i don't know how to cut it out in a view.
I need a complete example on how to do it please.
Thanks in advance
Even though there is an answer, i'd like to share my way:
// Let's say that you have an outlet to the image view called imageView
// Create the white view
let whiteView = UIView(frame: imageView.bounds)
let maskLayer = CAShapeLayer() //create the mask layer
// Set the radius to 1/3 of the screen width
let radius : CGFloat = imageView.bounds.width/3
// Create a path with the rectangle in it.
let path = UIBezierPath(rect: imageView.bounds)
// Put a circle path in the middle
path.addArcWithCenter(imageView.center, radius: radius, startAngle: 0.0, endAngle: CGFloat(2*M_PI), clockwise: true)
// Give the mask layer the path you just draw
maskLayer.path = path.CGPath
// Fill rule set to exclude intersected paths
maskLayer.fillRule = kCAFillRuleEvenOdd
// By now the mask is a rectangle with a circle cut out of it. Set the mask to the view and clip.
whiteView.layer.mask = maskLayer
whiteView.clipsToBounds = true
whiteView.alpha = 0.8
whiteView.backgroundColor = UIColor.whiteColor()
//If you are in a VC add to the VC's view (over the image)
view.addSubview(whiteView)
// Annnnnd you're done.
//assume you create a UIImageView and content image before execute this code
let sampleMask = UIView()
sampleMask.frame = self.view.frame
sampleMask.backgroundColor = UIColor.black.withAlphaComponent(0.6)
//assume you work in UIViewcontroller
self.view.addSubview(sampleMask)
let maskLayer = CALayer()
maskLayer.frame = sampleMask.bounds
let circleLayer = CAShapeLayer()
//assume the circle's radius is 150
circleLayer.frame = CGRect(x:0 , y:0,width: sampleMask.frame.size.width,height: sampleMask.frame.size.height)
let finalPath = UIBezierPath(roundedRect: CGRect(x:0 , y:0,width: sampleMask.frame.size.width,height: sampleMask.frame.size.height), cornerRadius: 0)
let circlePath = UIBezierPath(ovalIn: CGRect(x:sampleMask.center.x - 150, y:sampleMask.center.y - 150, width: 300, height: 300))
finalPath.append(circlePath.reversing())
circleLayer.path = finalPath.cgPath
circleLayer.borderColor = UIColor.white.withAlphaComponent(1).cgColor
circleLayer.borderWidth = 1
maskLayer.addSublayer(circleLayer)
sampleMask.layer.mask = maskLayer
Here is sample code for how you can make a circle Mask for a UIView:
let sampleView = UIView(frame: UIScreen.mainScreen().bounds)
let maskLayer = CALayer()
maskLayer.frame = sampleView.bounds
let circleLayer = CAShapeLayer()
//assume the circle's radius is 100
circleLayer.frame = CGRectMake(sampleView.center.x - 100, sampleView.center.y - 100, 200, 200)
let circlePath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 200, 200))
circleLayer.path = circlePath.CGPath
circleLayer.fillColor = UIColor.blackColor().CGColor
maskLayer.addSublayer(circleLayer)
sampleView.layer.mask = maskLayer
Here is what I made in the playground:
The easiest way to do this would be to create a png image with partly transparent white around the outside and a clear circle in the middle. Then stack 2 image views on top of each other, with the masking image on top, and set its "opaque" flag to false.
You could also do this by creating a CAShapeLayer and set it up to use a translucent white color, then install a shape that is the square with the hole cut out of it shape. You'd install that shape layer on top of your image view's layer.
The most general-purpose way to do that would be to create a custom subclass of UIImageView and have the init method of your subclass create and install the shape layer. I just created a gist yesterday that illustrated creating a custom subclass of UIImageView. Here is the link: ImageViewWithGradient gist
That gist creates a gradient layer. It would be a simple matter to adapt it to create a shape layer instead, and if you modified the layoutSubviews method you could make it adapt the view and path if the image view gets resized.
EDIT:
Ok, I took the extra step of creating a playground that creates a cropping image view. You can find that at ImageViewWithMask on github
The resulting image for my playground looks like this:
class MakeTransparentHoleOnOverlayView: UIView {
#IBOutlet weak var transparentHoleView: UIView!
// MARK: - Drawing
override func draw(_ rect: CGRect) {
super.draw(rect)
if self.transparentHoleView != nil {
// Ensures to use the current background color to set the filling color
self.backgroundColor?.setFill()
UIRectFill(rect)
let layer = CAShapeLayer()
let path = CGMutablePath()
// Make hole in view's overlay
// NOTE: Here, instead of using the transparentHoleView UIView we could use a specific CFRect location instead...
path.addRect(transparentHoleView.frame)
path.addRect(bounds)
layer.path = path
layer.fillRule = kCAFillRuleEvenOdd
self.layer.mask = layer
}
}
override func layoutSubviews () {
super.layoutSubviews()
}
// MARK: - Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
}