Set frame (CGRect) per devices by count of characters - Swift 3 - swift

I'm creating label and characters, I want set frame (X, Y and width) of UILabel by characters and Y-axis is constant of all devices, so how can I set center of X-axis and controlling by count of characters, and width (50) gets smaller and bigger per device ??
This my code :
func createTarget(id: Int) {
listdata = dbHelpr.getDatabase(rowId: id)
for data in listdata {
let lengthOfChar : CGFloat = data.ans.length
let targetSize : CGFloat = self.view.frame.width / 2
var xAxis : CGFloat = self.view.frame.width / 2 + 55
let yAxis : CGFloat = self.view.frame.height / 2 + 70
let targetLabel = UILabel(frame: CGRect(x: xAxis, y: yAxis, width: 50, height: 5))
xAxis -= 50 + (lengthOfChar)
}
}
In this picture is my label its position is center of X-axis of iPhone 7 plus simulator and numbers of label it's per count of characters, so I want like this position (X, Y and width) in all devices and width gets smaller and biggest and if count of characters for example is 9 it's must be on center of X-axis and width must be gets smaller little and spaces right and left of device.
How can I do it ?!
Thank you :)

This is the solution :
func createTarget(id: Int) {
listdata = dbHelpr.getDatabase(rowId: id)
for data in listdata {
let lengthOfChar : CGFloat = data.ans.length
let yAxis : CGFloat = self.view.frame.height / 2 + 70
let width: CGFloat = view.frame.size.width - 40 // frame width
var targetWidth: CGFloat = (width - (lengthOfChar - 1) * 5) / lengthOfChar
if targetWidth > 50 {
targetWidth = 50
}
let totalWidth: CGFloat = (targetWidth * lengthOfChar) + ((lengthOfChar - 5) * 5)
for (indexTar, tar) in data.ans.characters.enumerated() {
let x : CGFloat = (width / 2) - (totalWidth / 2)
let xx : CGFloat = (CGFloat(indexTar) * targetWidth) + (CGFloat(indexTar) * 5) + 20
var xAxis : CGFloat = (x + xx)
xAxis = width - xAxis
let targetLabel = UILabel(frame: CGRect(x: xAxis, y: yAxis, width: targetWidth, height: 5))
targetLabel.backgroundColor = .white
targetLabel.layer.masksToBounds = true
targetLabel.layer.cornerRadius = 5
targetLabel.text = String(describing: tar)
targetLabel.textAlignment = .center
targetLabel.textColor = .white
self.view.addSubview(targetLabel)
}
}
}

Related

How can l set frames for 12 buttons with loop (programatically)?

I'm trying to make Concentration game (with matching cards) and my task is to set frames for the array of 12 UIButtons with for-loop (I tried to realize it with switches, but it wan't right as my mentor said).
So maybe you can help me with this. The code added below works correctly, but l have to escape of switch and make it works with the help of for-loop and universal formulas.
func setFrames() {
for i in 0...11{
var x = CGFloat()
var y = CGFloat()
switch i {
case 0...2:
y = 50
case 3...5:
y = (7/36 * view.bounds.height + 50);
case 6...8:
y = (7/18 * view.bounds.height + 50);
default:
y = (7/12 * view.bounds.height + 50);
}
switch i {
case 0, 3, 6, 9:
x = 1/18 * view.bounds.width; //20
case 1, 4, 7, 10:
x = 3/8 * view.bounds.width; //3/8
default:
x = 3/4 * view.bounds.width - 20;
}
buttonsArray[i].frame = CGRect(x: x, y: y, width: (1/4 * view.bounds.width), height: (1/6 * view.bounds.height))
}
}
You can use something like so:
func placeBtnsIn(frame: CGRect, padding: CGFloat) {
let numCols = 3
let numRows = 4
let buttonWidth = (frame.width - CGFloat(numCols - 1) * padding) / CGFloat(numCols)
let buttonHeight = (frame.height - CGFloat(numRows - 1) * padding) / CGFloat(numRows)
var x: CGFloat
var y: CGFloat
for row in 0...(numRows - 1) {
y = frame.origin.y + (buttonHeight + padding) * CGFloat(row)
for col in 0...(numCols - 1) {
x = frame.origin.x + (buttonWidth + padding) * CGFloat(col)
let button = UIButton()
button.frame = CGRect(x: x, y: y, width: buttonWidth, height: buttonHeight)
self.addSubview(button)
}
}
}
Then in your code use it like so:
placeBtnsIn(frame: yourFrame, padding: 5)
Where yourFrame is a rectangle in which buttons should be drawn, and padding is the distance between button "cells"

FSCalendar library selected Date Circle size issue

How we can increase the size of the selected date title circle in FSCalendar libraryas we can see in the image I want the circle bigger than current size
calendar.appearance.borderRadius = .someValue // I tried all Value of enum But it not works
Override FSCalendarCell layoutSubviews method.
Here is my code.
override func layoutSubviews() {
super.layoutSubviews()
let titleHeight: CGFloat = self.bounds.size.height * 4.1 / 5
var diameter: CGFloat = min(self.bounds.size.height * 5.2 / 8, self.bounds.size.width)
diameter = diameter > FSCalendarStandardCellDiameter ? (diameter - (diameter-FSCalendarStandardCellDiameter) * 0.5) : diameter
shapeLayer.frame = CGRect(x: (bounds.size.width - diameter) / 2,
y: (titleHeight - diameter) / 2,
width: diameter, height: diameter)
let path = UIBezierPath(roundedRect: shapeLayer.bounds, cornerRadius: shapeLayer.bounds.width * 0.5 * appearance.borderRadius).cgPath
if shapeLayer.path != path {
shapeLayer.path = path
}
}
Change the value titleHeight, diameter to increase/decrease the size of selected date circle.

SwiftUI - Scale, Zoom and Crop Image

Edited with link to repository.
I am using SwiftUI and so don't have access to the 'cropping view'. I am using gestures instead of ScrollView to capture a zoom level and offset (x and y) of an image. I am unable to return an image which crops properly based on these factors.
It seems as if SwiftUI itself might be a factor. Perhaps the offset of the image within the view needs to be accounted for in determining offsets and zoom levels?
I have the image and I have the following values from the gestures on the view to represent scale and x/y position:
#State var scale: CGFloat = 1.0
#State var currentPosition: CGSize = CGSize.zero
The current attempt, which gets closest for the function called:
func prepareImage( ) {
let imageToManipulate = UIImage(named: "landscape")
let currentPositionWidth = self.currentPosition.width
let currentPositionHeight = self.currentPosition.height
let zoomScale = self.scale
let imsize = imageToManipulate!.size
var scale : CGFloat = self.frameSize.width / imsize.width
if imsize.height * scale < self.frameSize.height {
scale = self.frameSize.height / imsize.height
}
let croppedImsize = CGSize(width: (self.frameSize.width/scale) / zoomScale, height: (self.frameSize.height/scale) / zoomScale)
let xOffset = (( imsize.width - croppedImsize.width ) / 2.0) - (currentPositionWidth / zoomScale)
let yOffset = (( imsize.height - croppedImsize.height) / 2.0) - (currentPositionHeight / zoomScale)
let croppedImrect: CGRect = CGRect(x: xOffset, y: yOffset, width: croppedImsize.width, height: croppedImsize.height)
let r = UIGraphicsImageRenderer(size:croppedImsize)
let croppedIm = r.image { _ in
imageToManipulate!.draw(at: CGPoint(x:-croppedImrect.origin.x, y:-croppedImrect.origin.y))
}
self.croppedImage = croppedIm
self.photoIsFinished = true
}
However, as you will see in the repository, when combining both zoom/scale and x/y offsets it is always 'off' a bit.
As well, when you try to crop to a square image the amount it is 'off' can be quite significant.
Thanks to Asperi's answer , I have implement a lightweight swiftUI library to crop image.Here is the library and demo.Here
The magic is below:
public var body: some View {
GeometryReader { proxy in
// ...
Button(action: {
// how to crop the image according to rectangle area
if self.tempResult == nil {
self.cropTheImageWithImageViewSize(proxy.size)
}
self.resultImage = self.tempResult
}) {
Text("Crop Image")
.padding(.all, 10)
.background(Color.blue)
.foregroundColor(.white)
.shadow(color: .gray, radius: 1)
.padding(.top, 50)
}
}
}
func cropTheImageWithImageViewSize(_ size: CGSize) {
let imsize = inputImage.size
let scale = max(inputImage.size.width / size.width,
inputImage.size.height / size.height)
let zoomScale = self.scale
let currentPositionWidth = self.dragAmount.width * scale
let currentPositionHeight = self.dragAmount.height * scale
let croppedImsize = CGSize(width: (self.cropSize.width * scale) / zoomScale, height: (self.cropSize.height * scale) / zoomScale)
let xOffset = (( imsize.width - croppedImsize.width) / 2.0) - (currentPositionWidth / zoomScale)
let yOffset = (( imsize.height - croppedImsize.height) / 2.0) - (currentPositionHeight / zoomScale)
let croppedImrect: CGRect = CGRect(x: xOffset, y: yOffset, width: croppedImsize.width, height: croppedImsize.height)
if let cropped = inputImage.cgImage?.cropping(to: croppedImrect) {
//uiimage here can write to data in png or jpeg
let croppedIm = UIImage(cgImage: cropped)
tempResult = croppedIm
result = Image(uiImage: croppedIm)
}
}
The answer was provided via the GitHub repository by juanj
let imageToManipulate = UIImage(named: "landscape")
let zoomScale = self.scale
let imsize = imageToManipulate!.size
var scale : CGFloat = self.frameSize.width / imsize.width
if imsize.height * scale < self.frameSize.height {
scale = self.frameSize.height / imsize.height
}
let currentPositionWidth = self.currentPosition.width / scale
let currentPositionHeight = self.currentPosition.height / scale
let croppedImsize = CGSize(width: (self.frameSize.width/scale) / zoomScale, height: (self.frameSize.height/scale) / zoomScale)
let xOffset = (( imsize.width - croppedImsize.width ) / 2.0) - (currentPositionWidth / zoomScale)
let yOffset = (( imsize.height - croppedImsize.height) / 2.0) - (currentPositionHeight / zoomScale)
let croppedImrect: CGRect = CGRect(x: xOffset, y: yOffset, width: croppedImsize.width, height: croppedImsize.height)
let r = UIGraphicsImageRenderer(size:croppedImsize)
let croppedIm = r.image { _ in
imageToManipulate!.draw(at: CGPoint(x:-croppedImrect.origin.x, y:-croppedImrect.origin.y))
}
self.croppedImage = croppedIm
self.photoIsFinished = true
The full code, demonstrating how to allow a user to zoom and pan an image within a frame in a SwiftUI view, and then crop the result to a new image can be viewed in the repository.

white borders around physicsbody of tiles in tileMapNode

I have a tileMapNode in which I want to assign a physics body to some tiles.
I use the following function:
static func addPhysicsBody(to tileMap: SKTileMapNode, and tileInfo: String){
let tileSize = tileMap.tileSize
let halfWidth = CGFloat(tileMap.numberOfColumns) / 2 * tileSize.width
let halfHeight = CGFloat(tileMap.numberOfRows) / 2 * tileSize.height
for column in 0..<tileMap.numberOfColumns{
for row in 0..<tileMap.numberOfRows{
let tileDefinition = tileMap.tileDefinition(atColumn: column, row: row)
let isCorrectTile = tileDefinition?.userData?[tileInfo] as? Bool
if isCorrectTile ?? false && tileInfo == "wall"{
let x = CGFloat(column) * tileSize.width - halfWidth
let y = CGFloat(row) * tileSize.height - halfHeight
let rect = CGRect(x: 0, y: 0, width: tileSize.width, height: tileSize.height)
let tileNode = SKShapeNode(rect: rect)
tileNode.position = CGPoint(x: x, y: y)
tileNode.physicsBody = SKPhysicsBody.init(rectangleOf: tileSize, center: CGPoint(x: tileSize.width / 2, y: tileSize.height / 2))
tileNode.physicsBody!.isDynamic = false
tileNode.physicsBody!.restitution = 0.0
tileNode.physicsBody!.categoryBitMask = Constants.PhysicsCategories.wall
tileNode.physicsBody!.collisionBitMask = Constants.PhysicsCategories.player | Constants.PhysicsCategories.npc
tileMap.addChild(tileNode)
}
}
}
}
This all is working well, but if I run the app now, the tiles where I assigned a physics body to, have white borders. view.showphysics is set to false.
Anyone an idea why there are white borders around the tiles? It looks like this:

how to draw tic tac toe board as UIView in swift?

In my UIViewController I have a single subclass of UIView in which I will draw a tic tac toe board. Somehow the dividers (the "#" shape) I'm drawing using UIBezierPath() are not dividing the board evenly. Instead of 1/3-1/3-1/3, the vertical dividers are closer to 45%-45%-10% even though the dimensions printouts make sense. What am I missing? Thanks
In my subclass:
import UIKit
#IBDesignable class GameBoardView: UIView {
override func drawRect(rect: CGRect) {
// set up gameBoard dimensions everytime drawRect() is called
setUpGameBoardCells()
self.frame = CGRectMake(gameBoardPosX, gameBoardPosY, gameBoardLength, gameBoardLength)
print("gameBoard.frame: x=\(self.frame.origin.x), y=\(self.frame.origin.y), h=\(self.frame.height), w=\(self.frame.width)\n")
// draw dividers & cells
var divider = UIBezierPath(rect: CGRect(x: cellWidth, y: 0, width: dividerWidth, height: gameBoardLength))
divider.lineWidth = 1
UIColor.orangeColor().setStroke()
divider.stroke()
divider = UIBezierPath(rect: CGRect(x: cellWidth * 2 + dividerWidth, y: 0, width: dividerWidth, height: gameBoardLength))
divider.stroke()
}
}
And this is how I set up the dimensions to handle any sized screens:
var screenSize = CGRect()
let screenMargin: CGFloat = 20 // to the edge
var gameBoardIsPortrait = Bool()
var gameBoardLength = CGFloat()
var gameBoardPosX = CGFloat()
var gameBoardPosY = CGFloat()
let cellsPerRow: Int = 3
var cellWidth = CGFloat()
let dividerWidthGuide: CGFloat = 0.02 // guideline % of gameBoardLength
var dividerWidth = CGFloat()
let debugPrint = true
func setUpGameBoardCells() {
screenSize = UIScreen.mainScreen().bounds
// gameBoard is a square
gameBoardIsPortrait = (screenSize.height >= screenSize.width ? true : false)
gameBoardLength = min(screenSize.height, screenSize.width) - screenMargin * 2
gameBoardPosX = (screenSize.width - gameBoardLength) / 2
gameBoardPosY = (screenSize.height - gameBoardLength) / 2
// want cells & dividers on gameBoard to be whole numbers
dividerWidth = round(gameBoardLength * dividerWidthGuide)
let cellsTotalWidth: Int = Int(gameBoardLength) - Int(dividerWidth) * (cellsPerRow - 1)
let dividerWidthFudge: CGFloat = (cellsTotalWidth % cellsPerRow == 1 ? -1 : (cellsTotalWidth % cellsPerRow == 2 ? 1 : 0))
dividerWidth += dividerWidthFudge
cellWidth = CGFloat((cellsTotalWidth - Int(dividerWidthFudge) * (cellsPerRow - 1)) / cellsPerRow)
if debugPrint {
print("setUpCellDivision()->\nscreen: h=\(screenSize.height), w=\(screenSize.width)")
print("gameBoardIsPortrait=\(gameBoardIsPortrait), gameBoardLength=\(gameBoardLength), gameBoardPosX=\(gameBoardPosX), gameBoardPosY=\(gameBoardPosY)")
print("cellWidth=\(cellWidth), dividerWidth=\(dividerWidth)\n")
}
}
What is bizarre is that in xcode it looks right:
But in simulator it looks like this:
The problem is the setting of the frame from within drawRect. This would especially be a problem if you have any auto-layout constraints defined for the view.
The laying out of a view and the drawing of that view are two different steps, and you should therefore separate that logic.
Personally, I'd set up auto-layout constraints on the view to make sure that it is square, centered, and had the correct spacing. Then the view rendering is simplified:
#IBDesignable class GameBoardView: UIView {
override func drawRect(rect: CGRect) {
setUpGameBoardCells()
UIColor.orangeColor().setStroke()
var divider = UIBezierPath(rect: CGRect(x: cellWidth, y: 0, width: dividerWidth, height: bounds.size.height))
divider.lineWidth = 1
divider.stroke()
divider = UIBezierPath(rect: CGRect(x: cellWidth * 2 + dividerWidth, y: 0, width: dividerWidth, height: bounds.size.height))
divider.lineWidth = 1
divider.stroke()
}
let cellsPerRow = 3
let dividerWidthGuide: CGFloat = 0.02 // guideline % of gameBoardLength
var cellWidth: CGFloat!
var cellHeight: CGFloat!
var dividerWidth: CGFloat!
func setUpGameBoardCells() {
let gameBoardLength = min(bounds.size.height, bounds.size.width)
dividerWidth = round(gameBoardLength * dividerWidthGuide)
let cellsTotalWidth: Int = Int(gameBoardLength) - Int(dividerWidth) * (cellsPerRow - 1)
let dividerWidthFudge: CGFloat = (cellsTotalWidth % cellsPerRow == 1 ? -1 : (cellsTotalWidth % cellsPerRow == 2 ? 1 : 0))
dividerWidth! += dividerWidthFudge
cellWidth = CGFloat((cellsTotalWidth - Int(dividerWidthFudge) * (cellsPerRow - 1)) / cellsPerRow)
}
}
That yields:
Clearly, just repeat for your horizontal separators, too.
The simplest way would be adding UIViews(as separator lines) on yellow UIView and constraint them properly. You don't have to write too much of code.I would suggest to avoid the code in such cases.
You can try this. Draw the lines by calculating the frame of the view. The following will resize according to the frame.
func drawRect(frame frame: CGRect = CGRect(x: 52, y: 30, width: 90, height: 75)) {
//// Bezier Drawing
let bezierPath = UIBezierPath()
UIColor.blackColor().setStroke()
bezierPath.lineWidth = 1
bezierPath.stroke()
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRect(x: frame.minX + floor(frame.width * 0.32778) + 0.5, y: frame.minY + floor(frame.height * 0.06000) + 0.5, width: floor(frame.width * 0.35000) - floor(frame.width * 0.32778), height: floor(frame.height * 0.92667) - floor(frame.height * 0.06000)))
UIColor.blackColor().setStroke()
rectanglePath.lineWidth = 1
rectanglePath.stroke()
//// Rectangle 3 Drawing
let rectangle3Path = UIBezierPath(rect: CGRect(x: frame.minX + floor(frame.width * 0.68333) + 0.5, y: frame.minY + floor(frame.height * 0.06000) + 0.5, width: floor(frame.width * 0.70556) - floor(frame.width * 0.68333), height: floor(frame.height * 0.92667) - floor(frame.height * 0.06000)))
UIColor.blackColor().setStroke()
rectangle3Path.lineWidth = 1
rectangle3Path.stroke()
//// Rectangle 5 Drawing
let rectangle5Path = UIBezierPath(rect: CGRect(x: frame.minX + floor(frame.width * 0.07222) + 0.5, y: frame.minY + floor(frame.height * 0.63333) + 0.5, width: floor(frame.width * 0.92778) - floor(frame.width * 0.07222), height: floor(frame.height * 0.66000) - floor(frame.height * 0.63333)))
UIColor.blackColor().setStroke()
rectangle5Path.lineWidth = 1
rectangle5Path.stroke()
//// Rectangle 6 Drawing
let rectangle6Path = UIBezierPath(rect: CGRect(x: frame.minX + floor(frame.width * 0.07222) + 0.5, y: frame.minY + floor(frame.height * 0.31333) + 0.5, width: floor(frame.width * 0.92778) - floor(frame.width * 0.07222), height: floor(frame.height * 0.34000) - floor(frame.height * 0.31333)))
UIColor.blackColor().setStroke()
rectangle6Path.lineWidth = 1
rectangle6Path.stroke()
}
It seems as if your constraints aren't set up correctly. Try redoing the constraints to see if that fixes things.