How to draw a line between two points over an image in swift 3? - swift

I am new to swift, I want to draw a line between 2 points over an image which I called mapView, I tried to use CGContext but got no result, any idea to help? Thanks.
UIGraphicsBeginImageContext(mapView.bounds.size)
let context : CGContext = UIGraphicsGetCurrentContext()!
context.addLines(between: [CGPoint(x:oldX,y:oldY), CGPoint(x:newX, y:newY)])
context.setStrokeColorSpace(CGColorSpaceCreateDeviceRGB())
context.setStrokeColor(UIColor.blue.cgColor.components!)
context.setLineWidth(3)
mapView?.image?.draw(at: CGPoint(x:0, y:0))
context.strokePath()
mapView.image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

One option is to add a sub view to your image view and add the line drawing code into its draw(_ rect: CGRect) method.
A sample playground implementation:
class LineView : UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.init(white: 0.0, alpha: 0.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(UIColor.blue.cgColor)
context.setLineWidth(3)
context.beginPath()
context.move(to: CGPoint(x: 5.0, y: 5.0)) // This would be oldX, oldY
context.addLine(to: CGPoint(x: 50.0, y: 50.0)) // This would be newX, newY
context.strokePath()
}
}
}
let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png")) // This would be your mapView, here I am just using a random image
let lineView = LineView(frame: imageView.frame)
imageView.addSubview(lineView)

Related

IBInspectable variable value is not changing in interface builder and simulator

I am creating custom parallelogram view and view is rendering fine with default offset value. But when i change the offset value from ib it's not working
#IBDesignable class CustomParallelogramView: UIView {
#IBInspectable var offset: Float = 10.0
var path = UIBezierPath()
lazy var shapeLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.path = path.cgPath
return layer
}()
override init(frame: CGRect) {
super.init(frame:frame)
drawParallelogram()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
drawParallelogram()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
drawParallelogram()
}
override func layoutSubviews() {
super.layoutSubviews()
updateFrame()
}
func drawParallelogram() {
print(offset)
path.move(to: CGPoint(x: bounds.minX + CGFloat(offset), y: bounds.minY))
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
path.addLine(to: CGPoint(x: bounds.maxX - CGFloat(offset), y: bounds.maxY))
path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
path.close()
self.layer.mask = shapeLayer
}
func updateFrame() {
shapeLayer.frame = bounds
}
}
I changed the offset value from IB but it doesn't changes IB and simulator
A couple of thoughts:
As Daniel said, you really want to call drawParallelgram in your offset observer.
Also, in layoutSubviews, you’re updating the frame of your shape layer. You want to reset its path and update your mask again.
You’re just adding more and more strokes to your UIBezierPath. You probably just want to make it a local variable and avoid adding more and more strokes to the existing path.
The prepareForInterfaceBuilder suggests some misconception about the purpose of this method. This isn’t for doing initialization when launching from IB. This is for doing some special configuration, above and beyond what is already done by the init methods, required by IB.
E.g. If you have a sophisticated chart view where you’ll be programmatically providing real chart data programmatically later, but you wanted to see something in IB, nonetheless, you might have prepareForInterfaceBuilder populate some dummy data, for example. But you shouldn’t repeat the configuration you already did in init methods.
It’s not relevant here (because I’m going to suggest getting rid of these init methods), but for what it’s worth, if I need to do configuration during init, I generally write two init methods:
override init(frame: CGRect = .zero) {
super.init(frame: frame)
<#call configure routine here#>
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
<#call configure routine here#>
}
Note that in init(frame:) I also supply a default value of .zero. That ensures that I’m covered in all three scenarios:
CustomView()
CustomView(frame:); or
if the storyboard calls CustomView(decoder:).
In short, I get three init methods for the price of two. Lol.
All that being said, you can greatly simplify this:
#IBDesignable public class CustomParallelogramView: UIView {
#IBInspectable public var offset: CGFloat = 10 { didSet { updateMask() } }
override public func layoutSubviews() {
super.layoutSubviews()
updateMask()
}
private func updateMask() {
let path = UIBezierPath()
path.move(to: CGPoint(x: bounds.minX + offset, y: bounds.minY))
path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY))
path.addLine(to: CGPoint(x: bounds.maxX - offset, y: bounds.maxY))
path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
path.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
layer.mask = shapeLayer
}
}
Try:
#IBInspectable var offset: Float = 10.0 {
didSet {
drawParallelogram()
}
}

I can't get an arc to fill in Swift 4

I have a class that makes a UIView of a circle. I when I add the circle to my view, it shows the red outline, but the interior is clear instead of black. I want it to have a black fill.
class CircleView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
context.setLineWidth(1.0);
UIColor.red.set()
let center = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
let radius = (frame.size.width - 10)/2
context.addArc(center: center, radius: radius, startAngle: 0.0, endAngle: .pi * 2.0, clockwise: true)
context.strokePath()
context.closePath()
context.setFillColor(UIColor.black.cgColor)
context.fillPath()
}
}
}
This is more easily solved with a UIBezierPath.
override func draw(_ rect: CGRect) {
let path = UIBezierPath(ovalIn: bounds)
path.lineWidth = 1
UIColor.red.setStroke()
UIColor.black.setFill()
path.fill()
path.stroke()
}
If you look to the documentation of strokePath():
The current path is cleared as a side effect of calling this function.
Basically, after stroking your path, your paths is reset and there is nothing to fill.
A workaround could be to save context.path first and then use context.addPath(path). However, I usually prefer to build a separate CGMutablePath first and then add it to the context.

Add gradient color to a custom UIView

I realized a custom UIView class to a realize a sort of trapeze; following code I had used to realize the class:
import UIKit
import ChameleonFramework
class PolygonalView: UIView
{
override init(frame: CGRect)
{
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
context.beginPath()
context.move(to: CGPoint(x: rect.minX, y: rect.minY))
context.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
context.addLine(to: CGPoint(x: rect.maxX, y: 171))
context.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
context.closePath()
context.setFillColor(FlatSkyBlue().cgColor)
context.fillPath()
}
}
Then in my UIViewController I had create my view:
let pol = PolygonalView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 196))
pol.backgroundColor = UIColor.clear
self.view.addSubview(pol)
I achieved my goal, yep! But a problem has arisen: if I set a gradient, this gradient cover all the rectangular frame of the view.
Following codes and image...
let gradientColor = CAGradientLayer()
gradientColor.frame = pol.bounds
gradientColor.colors = [FlatSkyBlue().cgColor, FlatSkyBlueDark().cgColor, FlatBlue().cgColor]
gradientColor.startPoint = CGPoint(x: 0, y: 0)
gradientColor.endPoint = CGPoint(x: 1, y: 1)
pol.layer.addSublayer(gradientColor)
Any solutions to adapt the gradient to the real shape of my View?
Set the gradientColor layer's mask property to CAShapeLayer() that has the correct shape filled with black
let mask = CAShapeLayer()
mask.frame = // to whatever size it should be
mask.path = yourShapeBezierHERE.cgPath
mask.fillColor = UIColor.black.cgColor
gradientColor.mask = mask

Swift creating a line inside a view that the user can resize

How can I create a simple line that I can control its originating point, but let the user determine where it ends?
I have a UIView on my storyboard and on top of this I want to insert a line. The line would be restricted to be within this particular view and would start vertically centered and from the left side.
I have buttons with a - and a + to allow the user to increase its length or decrease it.
I suppose the easiest method will be to a add another UIView (call it lineView) inside your main view, set it's width to whatever you want the width of your line to be and hook it up with an #IBOutlet. Then in your #IBAction methods for - and +, change the height of lineView
I found the answer here, How to draw a line between two points over an image in swift 3?
class LineView : UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.init(white: 0.0, alpha: 0.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
context.setStrokeColor(UIColor.blue.cgColor)
context.setLineWidth(3)
context.beginPath()
context.move(to: CGPoint(x: 5.0, y: 5.0)) // This would be oldX, oldY
context.addLine(to: CGPoint(x: 50.0, y: 50.0)) // This would be newX, newY
context.strokePath()
}
}
}
let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png")) // This would be your mapView, here I am just using a random image
let lineView = LineView(frame: imageView.frame)
imageView.addSubview(lineView)

Swift 3: Drawing a rectangle

I'm 3 days new to swift, and I'm trying to figure out how to draw a rectangle. I'm too new to the language to know the classes to extend and the methods to override, and I've looked around for sample code, but nothing seems to work (which I'm attributing to my use of swift 3).
What I'm trying now is:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let k = Draw(frame: CGRect(
origin: CGPoint(x: 50, y: 50),
size: CGSize(width: 100, height: 100)))
k.draw(CGRect(
origin: CGPoint(x: 50, y: 50),
size: CGSize(width: 100, height: 100)));
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class Draw: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let h = rect.height
let w = rect.width
var color:UIColor = UIColor.yellow()
var drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5))
var bpath:UIBezierPath = UIBezierPath(rect: drect)
color.set()
bpath.stroke()
print("it ran")
NSLog("drawRect has updated the view")
}
}
And that's not doing anything. Help.
In order to see the view, you need to create one and give it frame so that it knows how big to make it.
If you put your code in a Playground, and then add this line:
let d = Draw(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
You'll be able to click on the Quick View on the right, and then you'll see the view.
You can also add the view as a subview of view in your ViewController and then you'll see it on the iPhone:
override func viewDidLoad() {
super.viewDidLoad()
let k = Draw(frame: CGRect(
origin: CGPoint(x: 50, y: 50),
size: CGSize(width: 100, height: 100)))
// Add the view to the view hierarchy so that it shows up on screen
self.view.addSubview(k)
}
Note that you never call draw(_:) directly. It is called for you by Cocoa Touch to display the view.
Create a class, I put it in a separate Swift 3 file.
//
// Plot_Demo.swift
//
// Storyboard is not good in creating self adapting UI
// Plot_Demo creates the drawing programatically.
import Foundation
import UIKit
public class Plot_Demo: UIView
{
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func draw(_ frame: CGRect) {
let h = frame.height
let w = frame.width
let color:UIColor = UIColor.yellow
let drect = CGRect(x: (w * 0.25), y: (h * 0.25), width: (w * 0.5), height: (h * 0.5))
let bpath:UIBezierPath = UIBezierPath(rect: drect)
color.set()
bpath.stroke()
print("it ran")
NSLog("drawRect has updated the view")
}
}
Example of use in an UIViewController object:
override func viewDidLoad() {
super.viewDidLoad()
// Instantiate a new Plot_Demo object (inherits and has all properties of UIView)
let k = Plot_Demo(frame: CGRect(x: 75, y: 75, width: 150, height: 150))
// Put the rectangle in the canvas in this new object
k.draw(CGRect(x: 50, y: 50, width: 100, height: 100))
// view: UIView was created earlier using StoryBoard
// Display the contents (our rectangle) by attaching it
self.view.addSubview(k)
}
Run in an iPhone simulator and on an iPhone:
Used XCode Version 8.0 (8A218a), Swift 3, target iOS 10.0
This is another way of drawing Rectangle,
Step 1: Get rectangle path for given points
(Note: arrPathPoints must be 4 in count to draw rectangle),
func getPathPayer(arrPathPoints:[CGPoint]) throws -> CAShapeLayer {
enum PathError : Error{
case moreThan2PointsNeeded
}
guard arrPathPoints.count > 2 else {
throw PathError.moreThan2PointsNeeded
}
let lineColor = UIColor.blue
let lineWidth: CGFloat = 2
let path = UIBezierPath()
let pathLayer = CAShapeLayer()
for (index,pathPoint) in arrPathPoints.enumerated() {
switch index {
//First point
case 0:
path.move(to: pathPoint)
//Last point
case arrPathPoints.count - 1:
path.addLine(to: pathPoint)
path.close()
//Middle Points
default:
path.addLine(to: pathPoint)
}
}
pathLayer.path = path.cgPath
pathLayer.strokeColor = lineColor.cgColor
pathLayer.lineWidth = lineWidth
pathLayer.fillColor = UIColor.clear.cgColor
return pathLayer
}
Step 2: Usage, Call method like this,
override func viewDidLoad() {
super.viewDidLoad()
do {
let rectangleLayer = try getPathPayer(arrPathPoints: [
CGPoint(x: 110, y: 110), //Top-Left
CGPoint(x: 130, y: 110), //Top-Right
CGPoint(x: 130, y: 130), //Bottom-Right
CGPoint(x: 110, y: 130)]) //Bottom-Left
view.layer.addSublayer(rectangleLayer)
} catch {
debugPrint(error)
}
}
My version of how to draw a rectangle using Swift 5.
First create a class to do the drawing. It uses CoreGraphics to do the drawing, rather than UIKit.
import UIKit
class DrawRectangle: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
print("could not get graphics context")
return
}
context.setStrokeColor(UIColor.yellow.cgColor)
context.setLineWidth(2)
context.stroke(rect.insetBy(dx: 10, dy: 10))
}
}
Then put this in your ViewController's viewDidLoad()
let myView = DrawRectangle(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
self.view.addSubview(myView)