space between two circles when one cuts another - swift

I need to arrange two UIImageViews in the following way, where one cuts another with some space inbetween each other as shown in the following example:
I can't use borderWidth because I need transparency around the green circle. There is a background image view in my app, so with the borderWidth users would see a black border line around the image or they would see nothing if I use clearColor. Any suggestions?

You can use a layer mask to achieve this.
Swift 2.3
let mask = CAShapeLayer()
let path = CGPathCreateMutable()
let center = view.convertPoint(statusImageView.center, toView: profileImageView)
let radius = statusImageView.frame.width / 2 + 4
CGPathAddRect(path, nil, profileImageView.bounds)
CGPathAddArc(path, nil, center.x, center.y, radius, 0, CGFloat(2 * M_PI), false)
mask.fillRule = kCAFillRuleEvenOdd
mask.path = path
profileImageView.layer.mask = mask
profileImageView.clipsToBounds = true
Swift 3
let mask = CAShapeLayer()
let path = CGMutablePath()
path.addRect(profileImageView.bounds)
path.addArc(
center: view.convert(statusImageView.center, to: profileImageView),
radius: statusImageView.frame.width / 2 + 4,
startAngle: 0,
endAngle: CGFloat(2 * M_PI),
clockwise: false
)
mask.fillRule = kCAFillRuleEvenOdd
mask.path = path
profileImageView.layer.mask = mask
profileImageView.clipsToBounds = true
UPDATE
class MatchViewController: UIViewController {
// MARK: Outlets
#IBOutlet var matchedImageView: UIImageView!
#IBOutlet var profileImageView: UIImageView!
#IBOutlet var tickImageView: UIImageView!
// MARK: Properties
var innerContainer: UIView! { return profileImageView.superview }
var outerContainer: UIView! { return innerContainer?.superview }
// MARK: Lifecycle
override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent }
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let mask = CAShapeLayer(),
path = CGPathCreateMutable()
let center = outerContainer.convertPoint(tickImageView.center, toView: innerContainer),
radius = tickImageView.frame.width / 2 + 4
CGPathAddRect(path, nil, innerContainer.bounds)
CGPathAddArc(path, nil, center.x, center.y, radius, 0, CGFloat(2 * M_PI), false)
mask.fillRule = kCAFillRuleEvenOdd
mask.path = path
innerContainer?.layer.mask = mask
innerContainer?.clipsToBounds = true
}
}
Make sure your views are structured like this.
This should be the result. Should be.

You can use a clipping for the image, and a custom view instead of an UIImageView. For computing the clipping path you need the intersection of two circles.

Related

How to zoom crop image in selected area

I want to crop image from selected area this is the image area i want to crop
this is the result i try to crop
the image i crop is not like in the crop area.
i use scrollview to zoom and pan the imageView, this is how setup to crop image.
i use this method from this stackoverflow
class ALCroppedPhotoViewController: UIViewController {
#IBOutlet weak var containerImage: UIView!
#IBOutlet weak var overlayView: UIView!
#IBOutlet weak var previewImageView: UIImageView!
#IBOutlet weak var rectHoleView: UIView!
#IBOutlet weak var scrollView: UIScrollView!
var data: Data?
var rect: CGRect!
override func viewDidLoad() {
super.viewDidLoad()
previewImageView.image = UIImage(data: data ?? Data())
setupScrollView()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let midX = overlayView.bounds.midX
let midY = overlayView.bounds.midY
let center = CGPoint(x: midX, y: midY)
let size: CGFloat = 312
// Create the initial layer from the view bounds.
let maskLayer = CAShapeLayer()
maskLayer.frame = overlayView.bounds
// Create the path.
rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
let path = UIBezierPath(rect: overlayView.bounds)
maskLayer.fillRule = .evenOdd
// Append the overlay image to the path so that it is subtracted.
path.append(UIBezierPath(roundedRect: rect, cornerRadius: 20))
maskLayer.path = path.cgPath
// Set the mask of the view.
overlayView.layer.mask = maskLayer
}
private func setupScrollView() {
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 2.0
scrollView.delegate = self
}
func snapshot(in imageView: UIImageView, rect: CGRect) -> UIImage {
assert(imageView.contentMode == .scaleAspectFit)
let image = imageView.image!
// figure out what the scale is
let imageRatio = imageView.bounds.width / imageView.bounds.height
let imageViewRatio = image.size.width / image.size.height
let scale: CGFloat
if imageRatio > imageViewRatio {
scale = image.size.height / imageView.bounds.height
} else {
scale = image.size.width / imageView.bounds.width
}
// convert the `rect` into coordinates within the image, itself
let size = rect.size * scale
let origin = CGPoint(x: image.size.width / 2 - (imageView.bounds.midX - rect.minX) * scale,
y: image.size.height / 2 - (imageView.bounds.midY - rect.minY) * scale)
let scaledRect = CGRect(origin: origin, size: size)
// now render the image and grab the appropriate rectangle within
// the image’s coordinate system
let format = UIGraphicsImageRendererFormat()
format.scale = image.scale
format.opaque = false
return UIGraphicsImageRenderer(bounds: scaledRect, format: format).image { _ in
image.draw(at: .zero)
}
}
extension CGSize {
static func * (lhs: CGSize, rhs: CGFloat) -> CGSize {
return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
}
}
}
The image actually crop successfully, but failed if i try to zoom really closely. How i can crop if try to zoom closely.
This is where the crash start when i try to print
scrollView.zoomScale
extension ALCroppedPhotoViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
print(scrollView.zoomScale)
return previewImageView
}
}
UIScrollView has a property zoomScale that tells you how much you are currently zoomed in. You'll need to use that to adjust your scale property.

does anybody understand this paradox with swift frames?

In UIKIT I have two uiview's main view and uiview installed with storyboard at top with high in 1/3 of main View.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var TopView: UIView!
#IBOutlet weak var MiddleView: UIView!
#IBOutlet weak var BottomView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let t = Vvp(inView: TopView)
TopView.addSubview(t)
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: TopView.frame.maxX, y: 0))
bezierPath.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.lineWidth = 1.0
TopView.layer.addSublayer(shapeLayer)
}
}
second view:
func Vvp(inView: UIView)-> UIView {
let viewWithBeizer = UIView(frame: inView.frame)
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: inView.frame.maxX, y: 0))
bezierPath.close()
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath
// apply other properties related to the path
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.fillColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 1.0
viewWithBeizer.layer.addSublayer(shapeLayer)
return viewWithBeizer
}
both views work with the same frame, at storyboard all borders are at zero
why lines are not the same?
The problem has nothing to do with where the lines are being drawn...
The issue is that you are referring to frame when you should be using bounds, and you're setting the frames before auto-layout has configured your views.
Based on your screen-shots, you are laying out your views in Storyboard based on an iPhone model with a Notch... so, in viewDidLoad() your TopView has the frame that was set in Storyboard.
This is how it looks using an iPhone 13 Pro in Storyboard:
As you can see, even though the yellow TopView is constrained to the top of the safe area, its Y position is 44. So, your code in your func Vvp(inView: UIView) is setting the Frame Y-position to 44, instead of Zero.
If you add these 4 lines at the end of viewDidLoad():
TopView.layer.addSublayer(shapeLayer)
// move t (from Vvp(inView: TopView))
// 40-pts to the right
t.frame.origin.x += 40.0
// give it an orange background color
t.backgroundColor = .orange
// allow it to show outside the bounds of TopView
TopView.clipsToBounds = false
// bring TopView to the front of the view hierarchy
view.bringSubviewToFront(TopView)
The output on an iPad Touch 7th Gen looks like this:
as you can see, TopView's subview (the orange view) is much larger than TopView, and is showing up where you told it to: 44-pts from the top of TopView.
To use the code the way you've written it, you need to call that func - along with the shapeLayer code for TopView - later in the controller's lifecycle... such as in viewDidLayoutSubviews(). If you do that, though, you need to remember it will be called multiple times (any time the main view changes, such as on device rotation), so you'll want to make sure you don't repeatedly add new subviews and layers.
Here's a quick modification of your code:
class ViewController: UIViewController {
#IBOutlet weak var TopView: UIView!
#IBOutlet weak var MiddleView: UIView!
#IBOutlet weak var BottomView: UIView!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if TopView.subviews.count == 0 {
// we haven't added the subview or shape layer,
// so let's do that here
let t = Vvp(inView: TopView)
TopView.addSubview(t)
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: TopView.frame.maxX, y: 0))
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.lineWidth = 1.0
TopView.layer.addSublayer(shapeLayer)
}
}
func Vvp(inView: UIView)-> UIView {
let viewWithBeizer = UIView(frame: inView.bounds)
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0, y: 0))
bezierPath.addLine(to: CGPoint(x: inView.bounds.maxX, y: 0))
let shapeLayer = CAShapeLayer()
shapeLayer.path = bezierPath.cgPath
// apply other properties related to the path
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.fillColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 1.0
viewWithBeizer.layer.addSublayer(shapeLayer)
return viewWithBeizer
}
}
Result (blue line is not visible, because we've added the red line on top of it):
A better approach, though, is to A) use auto-layout constraints, and B) handle your shapeLayer logic inside a custom UIView subclass -- but that's another topic.
I think that this is a bug with iPod touch 7' emulator - with another emulators code works well. Below you can see the code from my question where I add 2px to red line.

Using Swift and CAShapeLayer() with masking, how can I avoid inverting the mask when masked regions intersect?

This question was challenging to word, but explaining the situation further should help.
Using the code below, I'm essentially masking a circle on the screen wherever I tap to reveal what's underneath the black UIView. When I tap, I record the CGPoint in an array to keep track of the tapped locations. For every subsequent tap I make, I remove the black UIView and recreate each tapped point from the array of CGPoints I'm tracking in order to create a new mask that includes all the previous points.
The result is something like this:
I'm sure you can already spot what I'm asking about... How can I avoid the mask inverting wherever the circles intersect? Thanks for your help!
Here's my code for reference:
class MiniGameShadOViewController: UIViewController {
//MARK: - DECLARATIONS
var revealRadius : CGFloat = 50
var tappedAreas : [CGPoint] = []
//Objects
#IBOutlet var shadedRegion: UIView!
//Gesture Recognizers
#IBOutlet var tapToReveal: UITapGestureRecognizer!
//MARK: - VIEW STATES
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: - USER INTERACTIONS
#IBAction func regionTapped(_ sender: UITapGestureRecognizer) {
let tappedPoint = sender.location(in: view)
tappedAreas.append(tappedPoint) //Hold a list of all previously tapped points
//Clean up old overlays before adding the new one
for subview in shadedRegion.subviews {
if subview.accessibilityIdentifier != "Number" {subview.removeFromSuperview()}
}
//shadedRegion.layer.mask?.removeFromSuperlayer()
createOverlay()
}
//MARK: - FUNCTIONS
func createOverlay(){
//Create the shroud that covers the orbs on the screen
let overlayView = UIView(frame: shadedRegion.bounds)
overlayView.alpha = 1
overlayView.backgroundColor = UIColor.black
overlayView.isUserInteractionEnabled = false
shadedRegion.addSubview(overlayView)
let path = CGMutablePath()
//Create the box that represents the inverse/negative area relative to the circles
path.addRect(CGRect(origin: .zero, size: overlayView.frame.size))
//For each point tapped so far, create a circle there
for point in tappedAreas {
path.addArc(center: point, radius: revealRadius, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: false)
path.closeSubpath() //This is required to prevent all circles from being joined together with lines
}
//Fill each of my circles
let maskLayer = CAShapeLayer()
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.path = path;
maskLayer.fillRule = .evenOdd
//Cut out the circles inside that box
overlayView.layer.mask = maskLayer
overlayView.clipsToBounds = true
}
}
You asked:
how can I avoid inverting the mask when masked regions intersect?
In short, do not use the .evenOdd fill rule.
You have specified a fillRule of .evenOdd. That results in intersections of paths to invert. Here is a red colored view with a mask consisting of a path with two overlapping circular arcs with the .evenOdd rule:
If you use .nonZero (which, coincidentally, is the default fill rule for shape layers), they will not invert each other:
E.g.
class ViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
var maskLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.white.cgColor
return shapeLayer
}()
var points: [CGPoint] = [] // this isn't strictly necessary, but just in case you want an array of the points that were tapped
var path = UIBezierPath()
override func viewDidLoad() {
super.viewDidLoad()
imageView.layer.mask = maskLayer
}
#IBAction func handleTapGesture(_ gesture: UITapGestureRecognizer) {
let point = gesture.location(in: gesture.view)
points.append(point)
path.move(to: point)
path.addArc(withCenter: point, radius: 40, startAngle: 0, endAngle: .pi * 2, clockwise: true)
maskLayer.path = path.cgPath
}
}
Resulting in:

Custom shape to UISlider and update progress in Swift 5

I have checked some of the StackOverflow answers regarding custom UIView slider but using them I unable to make the slider like this. This makes a circle or half circle. I have figured out some library that makes circle slider using UIView but its not helpful to me so could anyone please help me out. How can I make slider like in below UIImage? Thanks!
You will probably just roll your own. (You obviously could search for third party implementations, but that would be out of scope for StackOverflow.) There are a lot of ways of tackling this, but the basic elements here are:
The pink arc for the overall path. Personally, I'd use a CAShapeLayer for that.
The white arc from the start to the current progress (measured from 0 to 1). Again, a CAShapeLayer would be logical.
The white dot placed at the spot of the current progress. Below I create a CALayer with white background and then apply a CAGradientLayer as a mask to that. You could also just create a UIImage for this.
In terms of how to set the progress, you would set the paths of the pink and white arcs to the same path, but just update the strokeEnd of the white arc. You would also adjust the position of the white dot layer accordingly.
The only complicated thing here is figuring out the center of the arc. In my example below, I calculate it with some trigonometry based upon the bounds of the view so that arc goes from lower left corner, to the top, and back down the the lower right corner. Or you might instead pass the center of the arc as a parameter.
Anyway, it might look like:
#IBDesignable
class ArcView: UIView {
#IBInspectable
var lineWidth: CGFloat = 7 { didSet { updatePaths() } }
#IBInspectable
var progress: CGFloat = 0 { didSet { updatePaths() } }
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
progress = 0.35
}
lazy var currentPositionDotLayer: CALayer = {
let layer = CALayer()
layer.backgroundColor = UIColor.white.cgColor
let rect = CGRect(x: 0, y: 0, width: lineWidth * 3, height: lineWidth * 3)
layer.frame = rect
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.white.cgColor, UIColor.clear.cgColor]
gradientLayer.type = .radial
gradientLayer.frame = rect
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 1)
gradientLayer.locations = [0.5, 1]
layer.mask = gradientLayer
return layer
}()
lazy var progressShapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineCap = .round
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
return shapeLayer
}()
lazy var totalShapeLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.lineCap = .round
shapeLayer.lineWidth = lineWidth
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = #colorLiteral(red: 0.9439327121, green: 0.5454334617, blue: 0.6426400542, alpha: 1)
return shapeLayer
}()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
override func layoutSubviews() {
super.layoutSubviews()
updatePaths()
}
}
// MARK: - Private utility methods
private extension ArcView {
func configure() {
layer.addSublayer(totalShapeLayer)
layer.addSublayer(progressShapeLayer)
layer.addSublayer(currentPositionDotLayer)
}
func updatePaths() {
let rect = bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)
let halfWidth = rect.width / 2
let height = rect.height
let theta = atan(halfWidth / height)
let radius = sqrt(halfWidth * halfWidth + height * height) / 2 / cos(theta)
let center = CGPoint(x: rect.midX, y: rect.minY + radius)
let delta = (.pi / 2 - theta) * 2
let startAngle = .pi * 3 / 2 - delta
let endAngle = .pi * 3 / 2 + delta
let path = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
progressShapeLayer.path = path.cgPath // white arc
totalShapeLayer.path = path.cgPath // pink arc
progressShapeLayer.strokeEnd = progress
let currentAngle = (endAngle - startAngle) * progress + startAngle
let dotCenter = CGPoint(x: center.x + radius * cos(currentAngle),
y: center.y + radius * sin(currentAngle))
currentPositionDotLayer.position = dotCenter
}
}
Above, I set the background color of the ArcView so you could see its bounds, but you would obviously set the background color to be transparent.
Now there are tons of additional features you might add (e.g. add user interaction so you could “scrub” it, etc.). See https://github.com/robertmryan/ArcView for example. But the key when designing this sort of stuff is to just break it down into its constituent elements, layering one on top of the other.
You can programmatically set the progress of the arcView to get it to change the current value between values of 0 and 1:
func startUpdating() {
arcView.progress = 0
var current = 0
Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { [weak self] timer in
current += 1
guard let self = self, current <= 10 else {
timer.invalidate()
return
}
self.arcView.progress = CGFloat(current) / 10
}
}
Resulting in:

How do I create a circle with CALayer?

I have the code below tested, but when I give it constraints it becomes a little small circle:
override func drawRect(rect: CGRect) {
var path = UIBezierPath(ovalInRect: rect)
fillColor.setFill()
path.fill()
//set up the width and height variables
//for the horizontal stroke
let plusHeight:CGFloat = 300.0
let plusWidth:CGFloat = 450.0
//create the path
var plusPath = UIBezierPath()
//set the path's line width to the height of the stroke
plusPath.lineWidth = plusHeight
//move the initial point of the path
//to the start of the horizontal stroke
plusPath.moveToPoint(CGPoint(
x:self.bounds.width/2 - plusWidth/2 + 0.5,
y:self.bounds.height/2 + 0.5))
//add a point to the path at the end of the stroke
plusPath.addLineToPoint(CGPoint(
x:self.bounds.width/2 + plusWidth/2 + 0.5,
y:self.bounds.height/2 + 0.5))
}
Change radius and fillColor as you want. :)
import Foundation
import UIKit
class CircleLayerView: UIView {
var circleLayer: CAShapeLayer!
override func draw(_ rect: CGRect) {
super.draw(rect)
if circleLayer == nil {
circleLayer = CAShapeLayer()
let radius: CGFloat = 150.0
circleLayer.path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2.0 * radius, height: 2.0 * radius), cornerRadius: radius).cgPath
circleLayer.position = CGPoint(x: self.frame.midX - radius, y: self.frame.midY - radius)
circleLayer.fillColor = UIColor.blue.cgColor
self.layer.addSublayer(circleLayer)
}
}
}
The rect being passed into drawRect is the area that needs to be updated, not the size of the drawing. In your case, you would probably just ignore the rect being passed in and set the circle to the size you want.
//// Oval Drawing
var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0, 0, 300, 300))
UIColor.whiteColor().setFill()
ovalPath.fill()
The only correct way to do it:
private lazy var whiteCoin: CAShapeLayer = {
let c = CAShapeLayer()
c.path = UIBezierPath(ovalIn: bounds).cgPath
c.fillColor = UIColor.white.cgColor
layer.addSublayer(c)
return c
}()
That literally makes a layer, as you wanted.
In iOS you must correctly resize any layers you are in charge of, when the view is resized/redrawn.
How do you do that? It is the very raison d'etre of layoutSubviews.
class ProperExample: UIView {
open override func layoutSubviews() {
super.layoutSubviews()
whiteCoin.frame = bounds
}
}
It's that simple.
class ProperExample: UIView {
open override func layoutSubviews() {
super.layoutSubviews()
whiteCoin.frame = bounds
}
private lazy var whiteCoin: CAShapeLayer = {
let c = CAShapeLayer()
c.path = UIBezierPath(ovalIn: bounds).cgPath
c.fillColor = UIColor.white.cgColor
layer.addSublayer(c)
return c
}()
}