Is it possible to draw a clear SCNSphere with a bright red SCNSpotlight? - scenekit

The last few days I am struggling a bit with SceneKit. I am trying to plot a clear/transparent SCNSphere, with a red spotlight. It appears that my red spotlight is becoming transparant as well if I set my SCNSphere to transpararent / clear colour. Is it possible to unlink the SCNLight Node to the SCNSphereNode, so that the bright red colour of the spot remains if the SCNSphere is transparant? Images of both spheres are below the code.
My code:
func setupView() {
scene = SCNScene()
caliView.scene = scene
caliView.allowsCameraControl = true
caliView.backgroundColor = UIColor.clearColor()
let clearMaterial = SCNMaterial()
clearMaterial.diffuse.contents = UIColor(white: 0.9, alpha: 0.5)
clearMaterial.locksAmbientWithDiffuse = true
let shape = SCNSphere(radius: 5)
shape.materials = [clearMaterial]
let shapeNode = SCNNode(geometry: shape)
let spotLight = SCNLight()
spotLight.type = SCNLightTypeSpot
spotLight.color = UIColor.init(colorLiteralRed: 180, green: 0, blue: 0, alpha: 0.0)
let lightNode = SCNNode()
lightNode.light = spotLight
lightNode.position = SCNVector3(x: 0.0, y:0.0, z:15.0)
lightNode.orientation = SCNQuaternion(x: 0.0, y:0, z:30, w:0.0)
let ambientLight = SCNLight()
ambientLight.type = SCNLightTypeAmbient
ambientLight.color = UIColor(white: 0.8, alpha: 0.2)
let ambientNode = SCNNode()
ambientNode.light = ambientLight
shapeNode.position = SCNVector3(x: 0.0, y: 0.0, z: 0.0)
scene.rootNode.addChildNode(ambientNode)
scene.rootNode.addChildNode(shapeNode)
shapeNode.addChildNode(lightNode)
}
Darker sphere with bright red spotlight:
More transparent sphere with soft red spotlight:

In this line...
shapeNode.addChildNode(lightNode)
...you added the light node to the sphere node.
If you want to un-link them while still having them move together, you can create an empty SCNNode and add the other two SCNNode instances to it as children (the one for the light and the one for the sphere):
func setupView() {
scene = SCNScene()
caliView.scene = scene
caliView.allowsCameraControl = true
caliView.backgroundColor = UIColor.clearColor()
let clearMaterial = SCNMaterial()
clearMaterial.diffuse.contents = UIColor(white: 0.9, alpha: 0.5)
clearMaterial.locksAmbientWithDiffuse = true
let emptyNode = SCNNode()
let shape = SCNSphere(radius: 5)
shape.materials = [clearMaterial]
let shapeNode = SCNNode(geometry: shape)
let spotLight = SCNLight()
spotLight.type = SCNLightTypeSpot
spotLight.color = UIColor.init(colorLiteralRed: 180, green: 0, blue: 0, alpha: 0.0)
let lightNode = SCNNode()
lightNode.light = spotLight
lightNode.position = SCNVector3(x: 0.0, y:0.0, z:15.0)
lightNode.orientation = SCNQuaternion(x: 0.0, y:0, z:30, w:0.0)
let ambientLight = SCNLight()
ambientLight.type = SCNLightTypeAmbient
ambientLight.color = UIColor(white: 0.8, alpha: 0.2)
let ambientNode = SCNNode()
ambientNode.light = ambientLight
shapeNode.position = SCNVector3(x: 0.0, y: 0.0, z: 0.0)
emptyNode.addChild(shapeNode)
emptyNode.addChild(lightNode)
scene.rootNode.addChildNode(emptyNode)
scene.rootNode.addChildNode(ambientNode)
}

Related

How to change colors of a cell of collection view on scrolling swift5

i want to change color of the cell of my collectionview on scrolling in swift.
here is an image of my viewcontroller. i want to change background color of the specific cell to white on scroll. and i used animatedcollectionViewLayout for animation.
This may help you, call it in scrollViewDidScroll. Don't use indexPathsForVisibleItems、visibleCells, they have a few issues.
func updateCellsApperance() {
let visibleRect = CGRect(origin: modesCollectionView.contentOffset, size: modesCollectionView.frame.size)
let center = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
var indexPaths: Set<IndexPath> = []
let step = 10.0
var x = center.x
while x > visibleRect.minX {
if let indexPath = modesCollectionView.indexPathForItem(at: CGPoint(x: x, y: center.y)) {
indexPaths.insert(indexPath)
}
x -= step
}
x = center.x + step
while x < visibleRect.maxX {
if let indexPath = modesCollectionView.indexPathForItem(at: CGPoint(x: x, y: center.y)) {
indexPaths.insert(indexPath)
}
x += step
}
indexPaths.forEach { indexPath in
if let cell = modesCollectionView.cellForItem(at: indexPath),
let attrs = modesCollectionView.layoutAttributesForItem(at: indexPath) {
let distanceX = visibleRect.midX - attrs.center.x
// >= 0.0
let ratio = abs(distanceX) * (1.0 / attrs.frame.width)
cell.xxx.color = UIColor(red: 0.0, green: max(0.0, 1.0 - ratio), blue: 0, alpha: 1.0)
}
}
}

Graphic Points are not working outside of viewDidLoad

I've created a Graphic Class to show for user a graphic points choose accordingly with user information.
If I use the graphicView object and add points at viewDidLoad, the graphic is presented correctly, if not there, the graphic presents no data.
See below the code for the Graphics and the code when I am requesting to mark the points.
class GraphView: UIView {
private struct Constants {
static let cornerRadiusSize = CGSize(width: 8.0, height: 8.0)
static let margin: CGFloat = 40.0
static let topBorder: CGFloat = 30
static let bottomBorder: CGFloat = 40
static let colorAlpha: CGFloat = 0.3
static let circleDiameter: CGFloat = 5.0
}
//1 - the properties for the gradient
var startColor: UIColor = UIColor.rgb(red: 14, green: 40, blue: 80)
var endColor: UIColor = UIColor.rgb(red: 14, green: 40, blue: 80)
//Weekly sample data
var graphPoints: [Int] = [0]
override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: UIRectCorner.allCorners,
cornerRadii: Constants.cornerRadiusSize)
path.addClip()
//2 - get the current context
let context = UIGraphicsGetCurrentContext()!
let colors = [startColor.cgColor, endColor.cgColor]
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations: [CGFloat] = [0.0, 1.0]
//5 - create the gradient
let gradient = CGGradient(colorsSpace: colorSpace,
colors: colors as CFArray,
locations: colorLocations)!
//6 - draw the gradient
var startPoint = CGPoint.zero
var endPoint = CGPoint(x: 0, y: self.bounds.height)
context.drawLinearGradient(gradient,
start: startPoint,
end: endPoint,
options: CGGradientDrawingOptions(rawValue: 0))
//calculate the x point
let margin = Constants.margin
let columnXPoint = { (column:Int) -> CGFloat in
//Calculate gap between points
let spacer = (width - margin * 2 - 4) / CGFloat((self.graphPoints.count - 1))
var x: CGFloat = CGFloat(column) * spacer
x += margin + 2
return x
}
// calculate the y point
let topBorder: CGFloat = Constants.topBorder
let bottomBorder: CGFloat = Constants.bottomBorder
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.max()!
let columnYPoint = { (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
y = graphHeight + topBorder - y // Flip the graph
return y
}
// draw the line graph
UIColor.white.setFill()
UIColor.white.setStroke()
//set up the points line
let graphPath = UIBezierPath()
//go to start of line
graphPath.move(to: CGPoint(x:columnXPoint(0), y:columnYPoint(graphPoints[0])))
//add points for each item in the graphPoints array
//at the correct (x, y) for the point
for i in 1..<graphPoints.count {
let nextPoint = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
graphPath.addLine(to: nextPoint)
}
//Create the clipping path for the graph gradient
//1 - save the state of the context (commented out for now)
context.saveGState()
//2 - make a copy of the path
let clippingPath = graphPath.copy() as! UIBezierPath
//3 - add lines to the copied path to complete the clip area
clippingPath.addLine(to: CGPoint(x: columnXPoint(graphPoints.count - 1), y:height))
clippingPath.addLine(to: CGPoint(x:columnXPoint(0), y:height))
clippingPath.close()
//4 - add the clipping path to the context
clippingPath.addClip()
let highestYPoint = columnYPoint(maxValue)
startPoint = CGPoint(x:margin, y: highestYPoint)
endPoint = CGPoint(x:margin, y:self.bounds.height)
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
context.restoreGState()
//draw the line on top of the clipped gradient
graphPath.lineWidth = 3.0
graphPath.stroke()
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point.x -= Constants.circleDiameter / 2
point.y -= Constants.circleDiameter / 2
let circle = UIBezierPath(ovalIn: CGRect(origin: point, size: CGSize(width: Constants.circleDiameter, height: Constants.circleDiameter)))
circle.fill()
}
//Draw horizontal graph lines on the top of everything
let linePath = UIBezierPath()
//top line
linePath.move(to: CGPoint(x:margin, y: topBorder))
linePath.addLine(to: CGPoint(x: width - margin, y:topBorder))
//center line
linePath.move(to: CGPoint(x:margin, y: graphHeight/2 + topBorder))
linePath.addLine(to: CGPoint(x:width - margin, y:graphHeight/2 + topBorder))
//bottom line
linePath.move(to: CGPoint(x:margin, y:height - bottomBorder))
linePath.addLine(to: CGPoint(x:width - margin, y:height - bottomBorder))
let color = UIColor(white: 1.0, alpha: Constants.colorAlpha)
color.setStroke()
linePath.lineWidth = 1.0
linePath.stroke()
}
}
I am trying to mark the points accordingly with the user input - see below:
func budgetAvailableCalculationFunction() {
let bankValue = (userSalary as NSString).integerValue
let bankPorcentage: Int = 100
let expenses = (userExpenses as NSString).integerValue
let calculation1: Int = expenses * bankPorcentage
let calculation2: Int = calculation1 / bankValue
let cashPorcentageAvailable = calculation2
let value: [Int] = [expenses]
self.setupGraphy(points: value)
progressView.progress = 0.0
progress.completedUnitCount = Int64(cashPorcentageAvailable)
progressView.setProgress(Float(self.progress.fractionCompleted), animated: true)
progressView.progressTintColor = UIColor.rgb(red: 239, green: 75, blue: 92)
progressView.backgroundColor = UIColor.rgb(red: 239, green: 75, blue: 92)
progressView.trackTintColor = .white
progressView.clipsToBounds = false
progressView.translatesAutoresizingMaskIntoConstraints = false
progressView.layer.cornerRadius = 0
porcentageLabelForMonth.text = "\(Int(self.progress.fractionCompleted * 100)) %"
}
The setupGraphy is just a function that returns an array of indexes that the user adds it.
Please note that using the same function at the viewDidLoad works:
self.setupGraphy(points: [100, 400, 200, 250])
enter image description here
Anyone?
Code for viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.rgb(red: 245, green: 246, blue: 250)
tableView.delegate = self
tableView.dataSource = self
tableView.register(LastTransactionsCell.self, forCellReuseIdentifier: "LastTransactionsCell")
tableView.backgroundColor = .clear
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy - LLLL"
let nameOfMonth = dateFormatter.string(from: now)
currentMonthLabel.text = nameOfMonth
setupUIXViews()
fetchUserInfo()
//static data for now
*self.setupGraphy(points: [100, 400, 200, 250])*
DispatchQueue.main.asyncAfter(deadline: .now() + 2){
self.budgetAvailableCalculationFunction()
}
}
The way I managed to fix (seems like a temporary fix) is by creating a new Int variable at the top of the project and passing the fetch data from the DB to these variables. That way I can use them at viewDidLoad instead of inside the fetch function.

Removing SceneKit emission material?

In an effort to highlight hit items in my scene, I'm doing something like this:
func
highlight(note inNote: Int, highlight inHighlight: Bool)
{
let scene = self.scene as! MainEditorScene
let node = scene.noteNodes[inNote]
let geom = node.geometry!
if inHighlight
{
geom.firstMaterial?.emission.contents = NSColor(calibratedRed: 1.0, green: 1.0, blue: 1.0, alpha: 0.3)
}
else
{
geom.firstMaterial?.emission.contents = nil
}
}
Unfortunately, the objects turn white but never back to their original color. Can I not remove the emission contents like this? What should I do?
Make it transparent:
geom.firstMaterial?.emission.contents = UIColor.clear
Instead of:
geom.firstMaterial?.emission.contents = nil
in SceneKit a black color, i.e.(0.0, 0.0, 0.0), is often the default value for "nothing" (that is a contribution of 0 in the lighting equation)
geom.firstMaterial?.emission.contents = NSColor.black

Create an array of images then press button to remove one of the images in the array

I am creating a drawing app in Swift. I which every time a user draws a line on the UIImageVIew it rasterizes a new image. I would like to create an undo button which goes to the previous image in the array.
Here is my code -
func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {
// 1
UIGraphicsBeginImageContext(view.frame.size)
tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
let context = UIGraphicsGetCurrentContext()
// 2
context?.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
context?.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
// 3
context?.setBlendMode(CGBlendMode.normal)
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(brushWidth)
context?.setStrokeColor(UIColor(red:red, green:green, blue:blue, alpha: 1.0).cgColor)
// 4
context?.strokePath()
// 5
tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
tempImageView.alpha = opacity
UIGraphicsEndImageContext()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
swiped = true
if let touch = touches.first {
let currentPoint = touch.location(in: view)
drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if !swiped {
// draw a single point
drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
}
// Merge tempImageView into mainImageView
UIGraphicsBeginImageContext(mainImageView.frame.size)
mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height),blendMode: CGBlendMode.normal, alpha: 1.0)
tempImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: CGBlendMode.normal, alpha: opacity)
mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
tempImageView.image = nil
floaty.isHidden = false
postBtn.isHidden = false
resetBtn.isHidden = false
undoBtn.isHidden = false
dismissBtn.isHidden = false
}

Multiple MapKit overlay colours from array

How do I make each bubble a different colour?
Here is my array of colours:
var tableColors = [UIColor(red: 220.0/255.0, green: 95.0/255.0, blue: 19.0/255.0, alpha: 0.9), // Rust
UIColor(red: 255.0/255.0, green: 191.0/255.0, blue: 59.0/255.0, alpha: 0.9), // Yellow
UIColor(red: 255.0/255.0, green: 91.0/255.0, blue: 51.0/255.0, alpha: 0.9), // Red
UIColor(red: 0.0/255.0, green: 160.0/255.0, blue: 174.0/255.0, alpha: 0.9), // KAL
UIColor(red: 0.0/255.0, green: 121.0/255.0, blue: 95.0/255.0, alpha: 0.9), // Green
UIColor(red: 104.0/255.0, green: 68.0/255.0, blue: 88.0/255.0, alpha: 0.9), // Purple
UIColor(red: 244.0/255.0, green: 97.0/255.0, blue: 119.0/255.0, alpha: 0.9), // Pink
UIColor(red: 1.0/255.0, green: 116.0/255.0, blue: 200.0/255.0, alpha: 0.9), // Blue
UIColor(red: 0.0/255.0, green: 188.0/255.0, blue: 111.0/255.0, alpha: 0.9), // Light Green
UIColor(red: 0.0/255.0, green: 196.0/255.0, blue: 179.0/255.0, alpha: 0.9), // Aqua
UIColor(red: 246.0/255.0, green: 50.0/255.0, blue: 62.0/255.0, alpha: 0.9)] // Hot
Here is the code which creates the locations from CloudKit data.
func fetchBubble() {
let query = CKQuery(recordType: "Collection", predicate: NSPredicate(format: "TRUEPREDICATE", argumentArray: nil))
publicDB!.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil {
for collection in results! {
let collectionLocation = collection.valueForKey("Location") as? CLLocation
let collectionName = collection.valueForKey("Name") as! String
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion.self) {
let intrepidLat: CLLocationDegrees = (collectionLocation?.coordinate.latitude)!
let intrepidLong: CLLocationDegrees = (collectionLocation?.coordinate.longitude)!
let title = collectionName
let coordinate = CLLocationCoordinate2DMake(intrepidLat, intrepidLong)
let regionRadius = 50.0
let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: coordinate.latitude,
longitude: coordinate.longitude), radius: regionRadius, identifier: title)
self.locationManager.startMonitoringForRegion(region)
let restaurantAnnotation = MKPointAnnotation()
self.mapView.addAnnotation(restaurantAnnotation)
restaurantAnnotation.coordinate = coordinate
let circle = MKCircle(centerCoordinate: coordinate, radius: regionRadius)
self.mapView.addOverlay(circle)
self.numberOfObjectsInMyArray()
}
else {
print("System can't track regions")
}
})
}
}
else {
print(error)
}
}
}
Then I draw the circles with the following code
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let circleRenderer = MKCircleRenderer(overlay: overlay)
for index in 1...5 {
circleRenderer.fillColor = self.tableColors[index + 1]
}
return circleRenderer
}
I've tried a few ways of looping through the colours but at the moment it is applying the same colour from the array to each of the bubbles.
Any help would be hugely appreciated!
In the rendererForOverlay callout method you are setting same last color to all the circleRenderer. So instead of your code
for index in 1...5 {
circleRenderer.fillColor = self.tableColors[index + 1]
}
replace with
circleRenderer.fillColor = self.randomTableColors()
And implement this method to give the random color as follow.
func randomTableColors() -> UIColor {
let randomIndex = Int(arc4random_uniform(UInt32(tableColors.count)))
return tableColors[randomIndex]
}

Resources