UIImageView cropping - swift

I am trying to allow users to crop an image. The problem is the cropped image is not the same as the view. Here are two screenshots to show what I mean.
pre crop screen:
!http://i58.tinypic.com/4rap9u.png
after crop
!http://i58.tinypic.com/2nrpjlj.png
Here is the code I use to create the new cropped image. The UIImageView is inside a UIScrollView to allow user to zoom and pan. Even when the image has not been zoomed it does not work correctly. Ideally I would like to allow the user to move the dashed square around the screen to select a portion of the image to crop, as well as zoom in/out.
func croppedImage() -> UIImage?
{
var drawRect: CGRect = CGRectZero
var cropRect : CGRect!
cropRect = photoFrameView?.frame
zoom = imgScroll.zoomScale
println(zoom)
drawRect.size = imgPreview.bounds.size
drawRect.origin.x = round(-cropRect.origin.x * zoom)
drawRect.origin.y = round(-cropRect.origin.y * zoom)
cropRect.size.width = round(cropRect.size.width*zoom)
cropRect.size.height = round(cropRect.size.height*zoom)
cropRect.origin.x = round(cropRect.origin.x)
cropRect.origin.y = round(cropRect.origin.y)
UIGraphicsBeginImageContextWithOptions(cropRect.size, false, UIScreen.mainScreen().scale)
self.imgPreview.image?.drawInRect(drawRect)
var result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return result
}
here is where I crop the image:
let cImg = croppedImage()!
UIImageWriteToSavedPhotosAlbum(cImg, nil, nil, nil);
imgPreview.image = cImg
self.imgPreview.contentMode = .ScaleAspectFit
Also here is the code for my UIView subclass(photoFrameView). Not sure if it is needed.
import UIKit
class mycropView: UIView {
var lastLocation:CGPoint = CGPointMake(0, 0)
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
var panRecognizer = UIPanGestureRecognizer(target:self, action:"detectPan:")
self.gestureRecognizers = [panRecognizer]
self.addDashedBorder()
self.backgroundColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func detectPan(recognizer:UIPanGestureRecognizer) {
var translation = recognizer.translationInView(self.superview!)
self.center = CGPointMake(lastLocation.x + translation.x, lastLocation.y + translation.y)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// Promote the touched view
self.superview?.bringSubviewToFront(self)
// Remember original location
lastLocation = self.center
}
override func hitTest(point: CGPoint, withEvent e: UIEvent?) -> UIView? {
if let result = super.hitTest(point, withEvent:e) {
println("hit inside")
return result
} else {
self.removeFromSuperview()
}
return nil
}
}
extension UIView {
func addDashedBorder() {
let color = UIColor.yellowColor().CGColor
let shapeLayer:CAShapeLayer = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = color
shapeLayer.lineWidth = 2
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPattern = [6,3]
shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).CGPath
self.layer.addSublayer(shapeLayer)
}
}

Related

How can I centre a circular progress bar in a UIView using Swift?

I'm having quite a bit of difficulty simply ensuring a circular progress bar is always in the centre of the UIView it is associated to.
This is what is happening:
Ignore the grey region, this is simply the UIView on a placeholder card. The red is the UIView I have added as an outlet to the UIViewController.
Below is the code for the class that I have made:
class CircleProgress: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
var progressLyr = CAShapeLayer()
var trackLyr = CAShapeLayer()
var progressClr = UIColor.red {
didSet {
progressLyr.strokeColor = progressClr.cgColor
}
}
var trackClr = UIColor.black {
didSet {
trackLyr.strokeColor = trackClr.cgColor
}
}
private func setupView() {
self.backgroundColor = UIColor.red
let centre = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
let circlePath = UIBezierPath(arcCenter: centre,
radius: 10,
startAngle: 0,
endAngle: 2 * CGFloat.pi,
clockwise: true)
trackLyr.path = circlePath.cgPath
trackLyr.fillColor = UIColor.clear.cgColor
trackLyr.strokeColor = trackClr.cgColor
trackLyr.lineWidth = 5.0
trackLyr.strokeEnd = 1.0
layer.addSublayer(trackLyr)
}
}
The aim is simply to have all 4 edges of the black circle touching the edges of the red square.
Any help is hugely appreciated. I'm thinking it must be too obvious but this has cost me too many hours tonight. :)
The problem is that there is no frame being passed when creating the object. No need for changing anything to your code. For sure you have to change the width and the height to whatever you want.
Here is an example...
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
// Add circleProgress
addCircleProgress()
}
private func addCircleProgress() {
let circleProgress = CircleProgress(frame: CGRect(x: self.view.center.x - 50, y: self.view.center.x - 50, width: 100, height: 100))
self.view.addSubview(circleProgress)
}
}
class CircleProgress: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var progressLyr = CAShapeLayer()
var trackLyr = CAShapeLayer()
var progressClr = UIColor.red {
didSet {
progressLyr.strokeColor = progressClr.cgColor
}
}
var trackClr = UIColor.black {
didSet {
trackLyr.strokeColor = trackClr.cgColor
}
}
private func setupView() {
self.backgroundColor = UIColor.red
let centre = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
let circlePath = UIBezierPath(arcCenter: centre,
radius: 50,
startAngle: 0,
endAngle: 2 * CGFloat.pi,
clockwise: true)
trackLyr.path = circlePath.cgPath
trackLyr.fillColor = UIColor.clear.cgColor
trackLyr.strokeColor = trackClr.cgColor
trackLyr.lineWidth = 5.0
trackLyr.strokeEnd = 1.0
layer.addSublayer(trackLyr)
}
}
A few suggestions:
I’d suggest making this CircularProgress take up the whole view. If you want this to be inset within the view, then, fine, add a property for that. In my example below, I created a property called inset to capture this value.
Make sure to update your path in layoutSubviews. Especially if you use constraints, you want this to respond to size changes. So add these layers from init, but update the path in layoutSubviews.
Don’t reference frame (which is the location within the superview coordinate system). Use bounds. And inset it by half the line width, so the circle doesn’t exceed the bounds of the view.
You created a progress color and progress layer, but didn’t use either one. I’ve guessed you wanted that to show the progress within the track.
You are stroking your path from 0 to 2π. People tend to expect these circular progress views to start from -π/2 (12 o’clock) and progress to 3π/2. So I’ve updated the path to use those values. But use whatever you want.
If you want, you can make it #IBDesignable if you want to see this rendered in IB.
Thus, pulling that together, you get:
#IBDesignable
public class CircleProgress: UIView {
#IBInspectable
public var lineWidth: CGFloat = 5 { didSet { updatePath() } }
#IBInspectable
public var strokeEnd: CGFloat = 1 { didSet { progressLayer.strokeEnd = strokeEnd } }
#IBInspectable
public var trackColor: UIColor = .black { didSet { trackLayer.strokeColor = trackColor.cgColor } }
#IBInspectable
public var progressColor: UIColor = .red { didSet { progressLayer.strokeColor = progressColor.cgColor } }
#IBInspectable
public var inset: CGFloat = 0 { didSet { updatePath() } }
private lazy var trackLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.fillColor = UIColor.clear.cgColor
layer.strokeColor = trackColor.cgColor
layer.lineWidth = lineWidth
return layer
}()
private lazy var progressLayer: CAShapeLayer = {
let layer = CAShapeLayer()
layer.fillColor = UIColor.clear.cgColor
layer.strokeColor = progressColor.cgColor
layer.lineWidth = lineWidth
return layer
}()
override init(frame: CGRect = .zero) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
public override func layoutSubviews() {
super.layoutSubviews()
updatePath()
}
}
private extension CircleProgress {
func setupView() {
layer.addSublayer(trackLayer)
layer.addSublayer(progressLayer)
}
func updatePath() {
let rect = bounds.insetBy(dx: lineWidth / 2 + inset, dy: lineWidth / 2 + inset)
let centre = CGPoint(x: rect.midX, y: rect.midY)
let radius = min(rect.width, rect.height) / 2
let path = UIBezierPath(arcCenter: centre,
radius: radius,
startAngle: -.pi / 2,
endAngle: 3 * .pi / 2,
clockwise: true)
trackLayer.path = path.cgPath
trackLayer.lineWidth = lineWidth
progressLayer.path = path.cgPath
progressLayer.lineWidth = lineWidth
}
}
That yields:
Update this function
private func setupView() {
self.backgroundColor = UIColor.red
let centre = CGPoint(x: bounds.midX, y: bounds.midY)
let circlePath = UIBezierPath(arcCenter: centre,
radius: bounds.maxX/2,
startAngle: 0,
endAngle: 2 * CGFloat.pi,
clockwise: true)
trackLyr.path = circlePath.cgPath
trackLyr.fillColor = UIColor.clear.cgColor
trackLyr.strokeColor = trackClr.cgColor
trackLyr.lineWidth = 5.0
trackLyr.strokeEnd = 1.0
layer.addSublayer(trackLyr)
}

How to generate a custom UIView that is above a UIImageView that has a circular hole punched in the middle that can see through to the UIImageView?

I am trying to punch a circular hole through a UIView that is above a UIImageView, whereby the hole can see through to the image below (I would like to interact with this image through the hole with a GestureRecognizer later). I have 2 problems, I cannot get the circular hole to centre to the middle of the UIImageView (it is currently centred to the top left of the screen), and that the effect that I am getting is the opposite to what i am trying to achieve (Everything outside of the circle is visible). Below is my code. Please can someone advise?
Result:
class UploadProfileImageViewController: UIViewController {
var scrollView: ReadyToUseScrollView!
let container: UIView = {
let view = UIView()
view.backgroundColor = UIColor.black
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let imgView: UIImageView = {
let imgView = UIImageView()
imgView.backgroundColor = UIColor.black
imgView.contentMode = .scaleAspectFit
imgView.image = UIImage.init(named: "soldier")!
imgView.translatesAutoresizingMaskIntoConstraints = false
return imgView
}()
var overlay: UIView!
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
private func setup(){
view.backgroundColor = UIColor.white
setupViews()
}
override func viewDidLayoutSubviews() {
overlay.center = imgView.center
print("imgView.center: \(imgView.center)")
overlay.layer.layoutIfNeeded() // I have also tried view.layoutIfNeeded()
}
private func setupViews(){
let s = view.safeAreaLayoutGuide
view.addSubview(imgView)
imgView.topAnchor.constraint(equalTo: s.topAnchor).isActive = true
imgView.leadingAnchor.constraint(equalTo: s.leadingAnchor).isActive = true
imgView.trailingAnchor.constraint(equalTo: s.trailingAnchor).isActive = true
imgView.heightAnchor.constraint(equalTo: s.heightAnchor, multiplier: 0.7).isActive = true
overlay = Overlay.init(frame: .zero, center: imgView.center)
print("setup.imgView.center: \(imgView.center)")
view.addSubview(overlay)
overlay.translatesAutoresizingMaskIntoConstraints = false
overlay.topAnchor.constraint(equalTo: s.topAnchor).isActive = true
overlay.leadingAnchor.constraint(equalTo: s.leadingAnchor).isActive = true
overlay.trailingAnchor.constraint(equalTo: s.trailingAnchor).isActive = true
overlay.bottomAnchor.constraint(equalTo: imgView.bottomAnchor).isActive = true
}
private func deg2rad( number: Double) -> CGFloat{
let rad = number * .pi / 180
return CGFloat.init(rad)
}
}
class Overlay: UIView{
var path: UIBezierPath!
var viewCenter: CGPoint?
init(frame: CGRect, center: CGPoint) {
super.init(frame: frame)
self.viewCenter = center
setup()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup(){
backgroundColor = UIColor.black.withAlphaComponent(0.8)
guard let path = createCirclePath() else {return}
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillRule = CAShapeLayerFillRule.evenOdd
self.layer.mask = shapeLayer
}
private func createCirclePath() -> UIBezierPath?{
guard let center = self.viewCenter else{return nil}
let circlePath = UIBezierPath()
circlePath.addArc(withCenter: center, radius: 200, startAngle: 0, endAngle: deg2rad(number: 360), clockwise: true)
return circlePath
}
private func deg2rad( number: Double) -> CGFloat{
let rad = number * .pi / 180
return CGFloat.init(rad)
}
}
CONSOLE:
setup.imgView.center: (0.0, 0.0)
imgView.center: (207.0, 359.0)
Try getting rid of the overlay you have and instead add the below UIView. It's basically a circular UIView with a giant black border, but it takes up the whole screen so the user can't tell. FYI, you need to use .frame to position items on the screen. The below puts the circle in the center of the screen. If you want the center of the image, replace self.view.frame with self. imgView.frame... Play around with circleSize and borderSize until you get the circle size you want.
let circle = UIView()
let circleSize: CGFloat = self.view.frame.height * 2 //must be bigger than the screen
let x = (self.view.frame.width / 2) - (circleSize / 2)
let y = (self.view.frame.height / 2) - (circleSize / 2)
circle.frame = CGRect(x: x, y: y, width: circleSize, height: circleSize)
let borderSize = (circleSize / 2) * 0.9 //the size of the inner circle will be circleSize - borderSize
circle.backgroundColor = .clear
circle.layer.cornerRadius = circle.frame.height / 2
circle.layer.borderColor = UIColor.black.cgColor
circle.layer.borderWidth = borderSize
view.addSubview(circle)

how to place image on top of uiview drawing (swift5)

My code below places a behind a drawing area. So as you can see in the image below. Anything I draw goes in front of the lines. I want to make so whatever i draw goes behind the lines. All of my code is attached below. The image is in the assets folder as well.
class ViewController: UIViewController {
var editBtn = UIButton()
var canVasView = UIView()
var path = UIBezierPath()
var startPoint = CGPoint()
var touchPoint = CGPoint()
func addArrowImageToButton(button: UIButton, arrowImage:UIImage = #imageLiteral(resourceName: "graph.png") ) {
let btnSize:CGFloat = 32
let imageView = UIImageView(image: arrowImage)
let btnFrame = button.frame
button.bringSubviewToFront(imageView)
}
override func viewDidAppear(_ animated: Bool) {
self.addArrowImageToButton(button: editBtn)
}
override func viewDidLoad() {
super.viewDidLoad()
setup()
draw()
view.addSubview(editBtn)
view.addSubview(canVasView)
editBtn.backgroundColor = UIColor.orange
canVasView.backgroundColor = UIColor.purple
editBtn.translatesAutoresizingMaskIntoConstraints = false
canVasView.translatesAutoresizingMaskIntoConstraints = false
let myLayer = CALayer()
let myImage = UIImage(named: "graph.png")?.cgImage
myLayer.frame = CGRect(x: 40, y: -80, width: 300, height: 300)
myLayer.contents = myImage
canVasView.layer.addSublayer(myLayer)
self.view.addSubview(canVasView)
NSLayoutConstraint.activate ([
canVasView.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :175),
canVasView.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 100),
canVasView.widthAnchor.constraint(equalToConstant: 350),
canVasView.heightAnchor.constraint(equalToConstant: 180),
editBtn.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :175),
editBtn.topAnchor.constraint(equalTo: view.centerYAnchor, constant : 0),
editBtn.widthAnchor.constraint(equalToConstant: 350),
editBtn.heightAnchor.constraint(equalToConstant: 180),
])
editBtn.addTarget(self, action: #selector(didTapEditButton), for: .touchUpInside)
}
#objc func didTapEditButton() {
path.removeAllPoints()
canVasView.layer.sublayers = nil
canVasView.setNeedsDisplay()
self.addArrowImageToButton(button: editBtn)
}
func setup(){
editBtn.layer.cornerRadius = 20
canVasView.clipsToBounds = true
canVasView.isMultipleTouchEnabled = false
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let point = touch?.location(in: canVasView){
startPoint = point
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let point = touch?.location(in: canVasView){
touchPoint = point
}
path.move(to: startPoint)
path.addLine(to: touchPoint)
startPoint = touchPoint
draw()
}
func draw() {
let strokeLayer = CAShapeLayer()
strokeLayer.fillColor = nil
strokeLayer.lineWidth = 5
strokeLayer.strokeColor = UIColor.blue.cgColor
strokeLayer.path = path.cgPath
canVasView.layer.addSublayer(strokeLayer)
canVasView.setNeedsDisplay()
}
}
To draw behind the lines image you need to add your stroke layer behind it.
To do so, declare myLayer outside of viewDidLoad then change your draw function to:
func draw() {
let strokeLayer = CAShapeLayer()
strokeLayer.fillColor = nil
strokeLayer.lineWidth = 5
strokeLayer.strokeColor = UIColor.blue.cgColor
strokeLayer.path = path.cgPath
canVasView.layer.insertSublayer(strokeLayer, below: myLayer) //draw behind myLayer
canVasView.setNeedsDisplay()
}

Draw Circle where user clicks with UIBezierPath

I am new to swift. I want to draw Circle on those pixels where user clicks.
Here is my code it is drawing circle but not at where I clicks....
I want to draw circle where user clicks....Like it is getting the coordinates where user clicks and printing them to console but I want to update the x and y arguments in ovalsandcircles() function.
Thanks in advance.
`import UIKit
class DemoView: UIView {
var startX :CGFloat = 0.0
var startY :CGFloat = 0.0
var path: UIBezierPath!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.darkGray
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
// Specify the fill color and apply it to the path.
ovalsAndCircles()
UIColor.orange.setFill()
path.fill()
Specify a border (stroke) color.
UIColor.purple.setStroke()
path.stroke()
}
func ovalsAndCircles () {
self.path = UIBezierPath(ovalIn: CGRect(x: startX,
y: startY,
width: 200,
height: 200))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let point = touches.first!.location(in: self)
startX = point.x
startY = point.y
print(startY)
print(startX)
}
}
`
(1) Add a UIView control through Interface Builder.
(2) Set the class name of that UIView control to DemoView.
(3) Create a subclass of UIView as DemoView as follows.
import UIKit
class DemoView: UIView {
let fillColor = UIColor.green
let strokeColor = UIColor.black
let radius: CGFloat = 100.0
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = event?.allTouches?.first
if let touchPoint = touch?.location(in: self) {
drawCircle(point: touchPoint)
}
}
func drawCircle(point: CGPoint) {
if let subLayers = self.layer.sublayers {
for subLayer in subLayers {
subLayer.removeFromSuperlayer()
}
}
let circlePath = UIBezierPath(arcCenter: point, radius: radius, startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2.0), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = fillColor.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
self.layer.addSublayer(shapeLayer)
}
}
First look at the Coordinate System in iOS: https://developer.apple.com/library/archive/documentation/General/Conceptual/Devpedia-CocoaApp/CoordinateSystem.html
The CGRect has a origin property of type CGPoint. Maybe it helps to set the origin of your rect in your draw function:
let rect: CGRect = ....
rect.origin = CGPoint(x:0.5, y:0.5) //Set the origin to the middle of the rect
You call the touchesBegan Method to set the points where it should be drawn. But when the user moves over the screen it wont be recognized. Use touchesEnded Method instead

Swift: how to implement a resizable personalized uiview with four buttons at vertexes

I would like to implement a resizable and draggable UIView like the following picture shows:
This is the class I have implemented up to now using simple gestures recognizers:
class PincherView: UIView {
var pinchRec:UIPinchGestureRecognizer!
var rotateRec:UIRotationGestureRecognizer!
var panRec:UIPanGestureRecognizer!
var containerView:UIView!
init(size: CGRect, container:UIView) {
super.init(frame: size)
self.containerView = container
self.pinchRec = UIPinchGestureRecognizer(target: self, action: "handlePinch:")
self.addGestureRecognizer(self.pinchRec)
self.rotateRec = UIRotationGestureRecognizer(target: self, action: "handleRotate:")
self.addGestureRecognizer(self.rotateRec)
self.panRec = UIPanGestureRecognizer(target: self, action: "handlePan:")
self.addGestureRecognizer(self.panRec)
self.backgroundColor = UIColor(red: 0.0, green: 0.6, blue: 1.0, alpha: 0.4)
self.userInteractionEnabled = true
self.multipleTouchEnabled = true
self.hidden = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handlePinch(recognizer : UIPinchGestureRecognizer) {
if let view = recognizer.view {
view.transform = CGAffineTransformScale(view.transform, 1.0, recognizer.scale)
//view.transform = CGAffineTransformScale(view.transform, recognizer.scale, recognizer.scale)
recognizer.scale = 1
}
}
func handleRotate(recognizer : UIRotationGestureRecognizer) {
if let view = recognizer.view {
view.transform = CGAffineTransformRotate(view.transform, recognizer.rotation)
recognizer.rotation = 0
}
}
func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(containerView)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPointZero, inView: containerView)
}
}
As you can imagine, with a simple UIPinchGestureRecognizer the uiview is scaled equally both in x and y directions but I want the users to have the chance to be as precise al possibile so that they can either scale even in one single direction or alter the form of the uiview, not necessarily to be a rectangle. Moreover, it's more important for me that user is as precise as possible in setting the heigth of the uiviewThat's why I need to have those 4 buttons at the corners.
I just would like you to give me some hints from where to start from and how.
Thank you
UPDATE
This is what I have done up to know
In this way I have the following hierarchy:
-UIImageView embed in
-UIView embed in
- UIScrollView embed in
- UIViewController
I had to add a further UIView to use as container, so that all sub uiviews it contains will be zoomed in/out together with the picture in order to have more precision in order to better overlap the azure uiview to photographed objects.
Concerning the pin, the little white circle, this is the class I have tried to implement up to know:
class PinImageView: UIImageView {
var lastLocation:CGPoint!
var container:UIView!
var viewToScale:UIView!
var id:String!
init(imageIcon: UIImage?, location:CGPoint, container:UIView, viewToScale:UIView, id:String) {
super.init(image: imageIcon)
self.lastLocation = location
self.frame = CGRect(x: location.x, y: location.y, width: 10.0, height: 10.0)
self.center = location
self.userInteractionEnabled = true
self.container = container
self.viewToScale = viewToScale
self.id = id
self.hidden = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func getScaleParameters(arrivalPoint:CGPoint) -> (sx:CGFloat, sy:CGFloat) {
//var result:(sx:CGFloat, sy:CGFloat) = (1.0, 1.0)
var scaleX:CGFloat = 1.0
var scaleY:CGFloat = 1.0
switch (self.id) {
case "up_left":
/* up_left is moving towards right*/
if (self.lastLocation.x < arrivalPoint.x) {
scaleX = -0.99
}
/* up_left is moving towards left*/
else {
scaleX = 0.9
}
/* up_left is moving towards up*/
if (self.lastLocation.y < arrivalPoint.y) {
scaleY = -0.9
}
/* up_left is moving towards down*/
else {
scaleY = 0.9
}
break
default:
scaleX = 1.0
scaleY = 1.0
}
return (scaleX, scaleY)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch: UITouch = touches.first {
let scaleParameters:(sx:CGFloat, sy:CGFloat) = self.getScaleParameters(touch.locationInView(self.container))
self.viewToScale.transform = CGAffineTransformMakeScale(scaleParameters.sx, scaleParameters.sy)
//self.center = touch.locationInView(self.container)
self.center = touch.locationInView(self.container)
self.lastLocation = touch.locationInView(self.container)
}
}
}
where viewToScale is the azure floating uiview called pincherViewRec. The center of the pin at the beginning is in pincherViewRec.frame.origin. It's useless to say that it does not work as expected.
Do you have any idea? Any hint would be appreciated to help me getting the right way.