What happened to CGRectGetMidX() and CGRectGetMidY()? - swift

I'm following a SpriteKit tutorial video from Rob Percival, and this line of code does not compile. It seems the syntax is out of date for getting the "mid x" and "mid y" values. What are the replacements for CGRectGetMidX() and CGRectGetMidY()?
CGPoint(x: CGRectGetMidX(self.frame),y: CGRectGetMidY(self.frame))

The syntax for just about everything changed with Swift 3.
You want:
man.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
See the documentation for CGRect for more details.

Related

How to fix refreshPreferences Message in Xcode 9 [duplicate]

This question already has answers here:
refreshPreferences HangTracerEnabled / HangTracerDuration messages in iOS 11 + Xcode 9
(3 answers)
Closed 5 years ago.
add this line code to my class
let myLayer = CALayer()
myLayer.contents = self.makeTrySwiftLogoImage().CGImage
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -500
transform = CATransform3DRotate(transform, 45.0f * M_PI / 180.0, 0, 1, 0)
myLayer.transform = transform
and get this message to my console
2017-09-22 18:00:53.354890+0330 SibDiet[973:944502] refreshPreferences: HangTracerEnabled: 0
2017-09-22 18:00:53.355974+0330 SibDiet[973:944502] refreshPreferences: HangTracerDuration: 500
2017-09-22 18:00:53.356014+0330 SibDiet[973:944502] refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0
and don't run my application, remove this 6 line and run again but receive this message again, remove Xcode and install again but no fix
I managed to fix it on High Sierra(10.13.1) XCode 9.1 and with iOS 11.0.3 by defining OS_ACTIVITY_MODE as disable by going in XCode via
Product > Scheme > Edit Scheme > Arguments > Environment Variables
add OS_ACTIVITY_MODE disable
schema editor (fragment)
Note: NSLog may not work after doing this.
Similar issue is reported in the question:
refreshPreferences HangTracerEnabled / HangTracerDuration messages in iOS 11 + Xcode 9

SKTexture nearest filtering mode doesn't work (Making Pixel Art)

I used a relatively small image (44pixel tall) and scaled it up to have a pixel art look. I tried to change the filtering mode to nearest so the anti-aliasing would disappear but it didn't. It appears with blurry edges. I tried the same with a background getting the same result.
let myNode = SKSpriteNode()
class GameScene: SKScene {
func makeNode() {
myNode.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
myNode.size = CGSize(width: 200, height: 200)
myNode.texture = SKTexture(imageNamed: "image")
myNode.texture!.filteringMode = .Nearest
return self.addChild(myNode)
}
}
override func didMoveToView(view: SKView) {
makeNode()
}
UPDATE:
SKTexture nearest filtering mode is now working in Xcode 7 GM. No need to manually scale images as I've suggested below.
I am experiencing this same problem in Xcode 7 beta 5 with beta iOS 9 ; the Nearest filtering mode is seemingly ignored. In my project, scaling with nearest-neighbor scaling was previously working in Xcode 6 on iOS 8.
In the event that the bug is not resolved before the final release of iOS 9 I am pre-scaling images before I place them in their respective atlases.
To do this I wrote a simple python script to recursively find png files and scale them using imagmagick.
If you don’t have imagemagick installed, you can install it using macports like so:
sudo port install ImageMagick
If you have homebrew it looks like this:
brew install imagemagick
I just place this script (below) in a file called imgscaler.py within the directory above my atlas files (which I want to scale by 400% in my case) and kick it off from the terminal:
python imgscaler.py
The script looks like this:
import subprocess
import os
import sys
import fnmatch
def main():
execution_folder_name = os.getcwd()
file_extension_name = "png"
#
# Collect names of files that will be manipulated
matches = []
for root, dirNames, fileNames in os.walk(execution_folder_name):
for filename in fnmatch.filter(fileNames, '*.' + file_extension_name):
full_name = os.path.join(root, filename)
matches.append(full_name)
scale_percentage = "400"
if not __query_yes_no("This script will scale images by " + scale_percentage + "% recursively from directory " + execution_folder_name + ". Proceed?"):
return
#
# Scale the images
for match in matches:
execution_str = "convert " + match + " -interpolate Nearest -filter point -resize " + scale_percentage + "% " + match + "\n"
sys.stdout.write(execution_str)
__run_command(execution_str)
def __run_command(input_cmd):
"""Runs a command on the terminal, and returns the output in a string array.
"""
process = subprocess.Popen(input_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
output = []
while True:
line = process.stdout.readline()
if line != '':
output.append(line)
else:
break
return output
def __query_yes_no(question, default="yes"):
"""Asks a yes or no question, returns a true is answered "yes".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
sys.stdout.flush()
choice = raw_input().lower()
if default is not None and choice == '':
sys.stdout.write(default)
sys.stdout.write('\n')
sys.stdout.flush()
return valid[default]
elif choice in valid:
sys.stdout.write(choice)
sys.stdout.write('\n')
sys.stdout.flush()
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
sys.stdout.flush()
main()
Change scale_percentage to whatever percentage you want to scale by.
BTW, I am guessing this scaling issue will eventually get resolved. I’m currently updating my code with this assumption in mind. This is just a bandaid in the event the fix to nearest-neighbor scaling in SpriteKit arrives later than iOS 9.0.
This is a bug in Xcode7 beta / iOS9. It works if you use Xcode 6.

How to draw on canvas using Cairo and GTK in Julia

I'm trying to use Julia with GTK and Cairo to draw onto a canvas. I think the following code (adapted from the example fragments on the GTK.jl page) should work, but it does not. (Other GTK widgets work, but not the canvas)
I would appreciate if someone can suggest what is wrong with this code, or give a pointer to a complete example.
using Gtk.ShortNames
using Cairo
function drawfn(w)
ctx = Gtk.getgc(w)
Cairo.set_coords(ctx, 0, 0, 800, 600, 0, 800, 0, 600)
h = Gtk.height(w)
w = Gtk.width(w)
Gtk.rectangle(ctx, 0, 0, w/2, h/2)
Gtk.set_source_rgb(ctx, 0, 0, 1)
Gtk.fill(ctx)
end
function main()
win = Gtk.#Window("stuff", 800,600)
c = Gtk.#Canvas()
Gtk.push!(win,c)
Gtk.draw(drawfn, c)
Gtk.showall(win)
end
main()
I think this was a bug in version 0.8.1 of Gtk.jl. I posted an issue to github after which vtjnash fixed it immediately and tagged version 0.8.2.

SpriteKit detecting non-existent contact

SpriteKit is reporting contact where none exists. I set a breakpoint in didBeginContact and found this:
(lldb) po contact.bodyA <SKPhysicsBody> type:<Rectangle> representedObject:[<SKSpriteNode> name:'5' texture:[<SKTexture> 'Brick_3.png' (60 x 60)] position:{600, 120} size:{60, 60} rotation:0.00]
(lldb) po contact.bodyB <SKPhysicsBody> type:<Rectangle> representedObject:[<SKSpriteNode> name:'bullet' texture:['nil'] position:{568.67426, 86.000015} size:{15, 8} rotation:0.00]
(lldb) p bodyB.usesPreciseCollisionDetection (BOOL) $10 = YES
BodyA is not moving.
BodyB is running an action that moves it in the positive X direction. Its y value is not changing.
Can anybody tell why it would think these 2 bodies are in contact?

CGPath not visible

I want to create a CGPath to look like a trail in an overview perspective. I have the following code in a UIView subclass. I know I am entering the methods through NSLogs. The CGPath doesn't appear on the screen.
- (void)drawRect:(CGRect)rect{
CGMutablePathRef p = CGPathCreateMutable();
CGPathMoveToPoint( p, NULL , 150 , 150 );
CGPathMoveToPoint( p, NULL , 300 , 300 );
CGPathMoveToPoint( p, NULL , 100 , 150 ) ;
CGPathMoveToPoint( p, NULL , 150 , 150 );
CGPathAddLineToPoint( p, NULL , 300 , 300 );
CGPathAddLineToPoint( p, NULL , 100 , 150 ) ;
CGPathAddLineToPoint( p, NULL , 150 , 150 );
CGPathCloseSubpath( p ) ;
CGContextRef context=UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextAddPath ( context, p ) ;
CGContextSaveGState(context);
CGColorRef redColor = [UIColor colorWithRed:1.0 green:12.0 blue:0.0 alpha:0.0].CGColor;
CGContextSetFillColorWithColor(context, redColor);
CGContextSetLineWidth(context, 20.0);
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextStrokePath(context);
CGContextFillPath ( context ) ;
CGContextDrawPath(context, kCGPathFill);
CGContextRestoreGState(context);
}
Nothing shows up
In advance thanks
The frameworks ensure that in -drawRect: there is already an appropriate graphics context set up for you and pointed at the display device. You only need UIGraphicsBeginImageContext()/UIGraphicsEndImageContext() if you are setting up to render someplace else, such as to an image.
Delete those calls and things will behave a lot better. Right now you are rendering to an off-screen buffer, not to the view itself.
Edit: You should, however, add a pair of CGContextSaveGState() / CGContextRestoreGState() calls around your code, however. This will ensure you don't contaminate the graphics context for other graphics code if your -drawRect: is used in certain ways.
Edit 2: Alright, I see that you have resolved the issue after your last response, but for the benefit of archives, I am going to point out that you never call -drawRect: directly (except in some obscure cases that don't apply here). Since you had called it directly, no graphics context had been set up, hence the crash. The proper way to trigger redraw is to send the view -setNeedsDisplay; this will cause the frameworks to setup a graphics context and invoke -drawRect: for you at the appropriate time in the run loop.
If on iOS, switch to bezier paths using UIBezierPath. Sure-fire to work.
Also, I've noticed, each of your moveToPoints are in a single row, when they should have one addLineToPoint right after them, like so:
CGPathMoveToPoint(p, NULL, 150, 150);
CGPathAddLineToPoint( p, NULL, 300, 300);
CGPathMoveToPoint(p, NULL, 300, 300 ;
CGPathAddLineToPoint(p, NULL, 100, 150);
CGPathMoveToPoint(p, NULL, 100, 150);
CGPathAddLineToPoint(p, NULL, 100, 150);
CGPathMoveToPoint(p, NULL, 150, 150);
CGPathAddLineToPoint(p, NULL, 150, 150);
But you'll want to switch to UIBezierPaths anyway once you see how easy they are.