How can I remove a UIView with rounded corners from its parent view? - cocoa

I'm creating an iPad app for 3.2 and later. My app has an overlay view which has a semi-transparency that makes everything below it darker. In the middle of this view I am chopping a hole in this semi-transparency to let part of the background filter through unscathed, with this code:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect intersection = CGRectIntersection(hole.frame, rect);
CGContextClearRect(context, intersection);
}
Additionally, the 'hole' view has rounded corners, applied via:
self.layer.cornerRadius = 4.25;
This works great except for one small problem - these rounded corners are not taken into account, so the hole that gets chopped out has square corners instead of rounded. I need to fix this, but I have no idea how. Any ideas, examples, thoughts?

Here's how I ended up getting it to work. This produces a hole with the same frame as the 'hole' UIView, cutting it out from self (UIView). This lets you see whatever is behind the 'hole' unhindered.
- (void)drawRect:(CGRect)rect {
CGFloat radius = self.hole.layer.cornerRadius;
CGRect c = self.hole.frame;
CGContextRef context = UIGraphicsGetCurrentContext();
// this simply draws a path the same shape as the 'hole' view
CGContextMoveToPoint(context, c.origin.x, c.origin.y + radius);
CGContextAddLineToPoint(context, c.origin.x, c.origin.y + c.size.height - radius);
CGContextAddArc(context, c.origin.x + radius, c.origin.y + c.size.height - radius, radius, M_PI_4, M_PI_2, 1);
CGContextAddLineToPoint(context, c.origin.x + c.size.width - radius, c.origin.y + c.size.height);
CGContextAddArc(context, c.origin.x + c.size.width - radius, c.origin.y + c.size.height - radius, radius, M_PI_2, 0.0f, 1);
CGContextAddLineToPoint(context, c.origin.x + c.size.width, c.origin.y + radius);
CGContextAddArc(context, c.origin.x + c.size.width - radius, c.origin.y + radius, radius, 0.0f, -M_PI_2, 1);
CGContextAddLineToPoint(context, c.origin.x + radius, c.origin.y);
CGContextAddArc(context, c.origin.x + radius, c.origin.y + radius, radius, -M_PI_2, M_PI, 1);
// finish
CGContextClosePath(context);
CGContextClip(context); // this is the secret sauce
CGContextClearRect(context, c);
}

What you're trying to do is called masking. You can use Core Graphics to mask the current graphics context. See Apple's documentation on the subject here:
http://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/TP30001066-CH212-CJBHDDBE

If you change the cornerRadius property of a layer, you must also set clipsToBounds to YES on the associated view in order for the content to be clipped to the rounded corners.

Related

How to add labels onto segments of a circle in p5.js?

I’m working on a project with p5.js where I draw a circle, draw arcs (straight red lines) to separate the circle then another arc between each of the red lines (blue lines). The idea looks like the included image below:
What I'm confused about is how to position the labels in the circle drawing so that they're positioned in each segment inside the circle but outside the blue arcs. My question is how do I add text labels to this figure so that it looks like the image below?
Here is the shortened code to produce the first image (circle without the labels) so far:
function setup() {
createCanvas(400, 400);
}
function draw() {
background(255);
let startX = 50;
let startY = 50;
let data = [1, 2, 3, 4];
let width = 80;
let angle = -Math.PI / 2;
let radianPer = Math.PI * 2 / Object.keys(data).length;
noStroke();
fill(255);
ellipse(startX, startY, width, width);
Object.keys(data).forEach(i => {
fill(255);
stroke(255, 0, 0);
arc(startX, startY, width, width, angle, angle + radianPer, PIE);
fill(255);
stroke(0, 0, 255);
arc(startX, startY, width / 2, width / 2, angle, angle + radianPer, PIE);
angle += radianPer;
// add label here
});
}
Edit (02/05/22): updated code to match the screenshot image example.
Displaying a label in the middle of a segment of an arc involves using the angle for the middle of that arc with the sine and cosine functions to find the X and Y coordinates. For more information see the trigonometric functions article on wikipedia.
function setup() {
createCanvas(400, 400);
// Text settings
textAlign(CENTER, CENTER);
}
function draw() {
background(255);
let startX = 50;
let startY = 50;
let data = [1, 2, 3, 4];
let width = 80;
let angle = -Math.PI / 2;
let radianPer = (Math.PI * 2) / Object.keys(data).length;
noStroke();
fill(255);
ellipse(startX, startY, width, width);
Object.keys(data).forEach((i) => {
fill(255);
stroke(255, 0, 0);
arc(startX, startY, width, width, angle, angle + radianPer, PIE);
fill(255);
stroke(0, 0, 255);
arc(startX, startY, width / 2, width / 2, angle, angle + radianPer, PIE);
// add label here
let textAngle = angle + radianPer / 2;
// Use sine and cosine to determine the position for the text
// Since sine is opposite / hypotenuse, taking the sine of the angle and
// multiplying by distance gives us the vertical offset (i.e. the Y
// coordinate).
// Likewise with cosine for the X coordinate
noStroke();
fill(0);
text(
data[i].toString(),
startX + cos(textAngle) * width / 2 * 0.75,
startY + sin(textAngle) * width / 2 * 0.75
);
// Don't update angle until after calculating the angle for the label
angle += radianPer;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

Rotate a Sprite around another Sprite -libGDX-

video game link
I'm trying to make a game (see link above) , and I need to have the stick rotate around himself to maintain the orientation face to center of the circle.
this is how I declare the Sprite, and how I move it around the circle:
declaration:
line = new Sprite(new Texture(Gdx.files.internal("drawable/blockLine.png")));
line.setSize(140, 20);
lineX = Gdx.graphics.getWidth()/2 - line.getWidth()/2;
lineY = (Gdx.graphics.getHeight()/2 - line.getHeight()/2) + circle.getHeight()/2;
movement:
Point point = rotatePoint(new Point(lineX, lineY), new Point(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2), angle+= Gdx.graphics.getDeltaTime() * lineSpeed);
line.setPosition(point.x, point.y);
rotatePoint function:
Point rotatePoint(Point point, Point center, double angle){
angle = (angle ) * (Math.PI/180); // Convert to radians
float rotatedX = (int) (Math.cos(angle) * (point.x - center.x) - Math.sin(angle) * (point.y-center.y) + center.x);
float rotatedY = (int) (Math.sin(angle) * (point.x - center.x) + Math.cos(angle) * (point.y - center.y) + center.y);
return new Point(rotatedX,rotatedY);
}
Any sugestions ?
I can't test right now but I think the rotation of the line should simply be:
Math.atan2(rotatedPoint.getOriginX() - middlePoint.getOriginX(), rotatedPoint.getOriginY() - middlePoint.getOriginY()));
Then you'll have to adjust rad to degrees or whatever you'll use. Tell me if it doesn't work!
I would take a different approach, I just created a method that places n Buttons around a click on the screen. I am using something that looks like this:
float rotation; // in degree's
float distance; //Distance from origin (radius of circle).
vector2 originOfRotation; //Center of circle
vector2 originOfSprite; //Origin of rotation sprite we are calculating
Vector2 direction = new vector2(0, 1); //pointing up
//rotate the direction
direction.rotate(rotation);
// add distance based of the direction. Warning: originOfRotation will change because of chaining method.
// use originOfRotation.cpy() if you do not want to init each frame
originOfSprite = originOfRotation.add(direction.scl(distance));
Now you have the position of your sprite. You need to increment rotation by x each frame to have it rotate. If you want the orientation of the sprite to change you can use the direction vector, probably rotated by 180 again. Efficiency wise I'm not sure what the difference would be.

How to position a textured quad in screen coordinates?

I am experimenting with different matrices, studying their effect on a textured quad. So far I have implemented Scaling, Rotation, and Translation matrices fairly easily - by using the following method against my position vectors:
enter code here
for(int a=0;a<noOfVertices;a++)
{
myVectorPositions[a] = SlimDX.Vector3.TransformCoordinate(myVectorPositions[a],myPerspectiveMatrix);
}
However, I what I want to do is be able to position my vectors using world-space coordinates, not object-space.
At the moment my position vectors are declared thusly:
enter code here
myVectorPositions[0] = new Vector3(-0.1f, 0.1f, 0.5f);
myVectorPositions[1] = new Vector3(0.1f, 0.1f, 0.5f);
myVectorPositions[2] = new Vector3(-0.1f, -0.1f, 0.5f);
myVectorPositions[3] = new Vector3(0.1f, -0.1f, 0.5f);
On the other hand (and as part of learning about matrices) I have read that I need to apply a matrix to get to screen coordinates. I've been looking through the SlimDX API docs and can't seem to pin down the one I should be using.
In any case, hopefully the above makes sense and what I am trying to achieve is clear. I'm aiming for a simple 1024 x 768 window as my application area, and want to position a my textured quad at 10,10. How do I go about this? Most confused right now.
I am not familiar with slimdx, but in native DirectX, if you want to draw a quad in screen coordinates, you should define the vertex format as Translated, that is you specify the screen coordinates directly instead of using D3D transform engine to transform your vertex. the vertex definition as below
#define SCREEN_SPACE_FVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)
and you can define your vertex like this
ScreenVertex Vertices[] =
{
// Triangle 1
{ 150.0f, 150.0f, 0, 1.0f, 0xffff0000, }, // x, y, z, rhw, color
{ 350.0f, 150.0f, 0, 1.0f, 0xff00ff00, },
{ 350.0f, 350.0f, 0, 1.0f, 0xff00ffff, },
// Triangle 2
{ 150.0f, 150.0f, 0, 1.0f, 0xffff0000, },
{ 350.0f, 350.0f, 0, 1.0f, 0xff00ffff, },
{ 150.0f, 350.0f, 0, 1.0f, 0xff00ffff, },
};
By default screen space in 3d systems is from -1 to 1 (where -1,-1 is bottom left corner and 1,1 top right).
To convert those unit to pixel values, you need to convert pixel values into this space. So for example pixel 10,30 on a screen of 1024*768 is:
position.x = 10.0f * (1.0f / 1024.0f); // maps to 0/1
position.x *= 2.0f; //maps to 0/2
position.x -= 1.0f; // Maps to -1/1
Now for y you do
position.y = 30.0f * (1.0f / 768.0f); // maps to 0/1
position.y = 1.0f - position.y; //Inverts y
position.y *= 2.0f; //maps to 0/2
position.y -= 1.0f; // Maps to -1/1
Also if you want to apply transforms to your quads, It is better to send the transformation to the shader (and do the vector transformation in the vertex shader), rather than doing the multiplications on the vertices, since you will not need to update your vertexbuffer every time.

How to format table cell to have rounded corners?

I want rounded corners for my Table Cell View. So I just set the background to transparent but this removes the whole background of the cell.
Any idea how to do that using the visual editor?
There are some ways to achieve that:
override drawRect in your custom tableViewCell class. This is drawing by hand, very nasty ;) I'll post an example code below for a rounded corner background.
put an imageView in the background and add a picture with round corners to the cell. (Background is transparent of course). The problem with transparent backgrounds is performance.
example code for a backround with round corners
float radius = 10.0;
CGContextRef context = UIGraphicsGetCurrentContext();
rect = CGRectInset(rect, 1.0f, 1.0f);
CGContextBeginPath(context);
CGContextSetGrayFillColor(context, 0.0, 0.8);
CGContextMoveToPoint(context, CGRectGetMinX(rect) + radius, CGRectGetMinY(rect));
CGContextAddArc(context, CGRectGetMaxX(rect) - radius, CGRectGetMinY(rect) + radius, radius, 3 * M_PI / 2, 0, 0);
CGContextAddArc(context, CGRectGetMaxX(rect) - radius, CGRectGetMaxY(rect) - radius, radius, 0, M_PI / 2, 0);
CGContextAddArc(context, CGRectGetMinX(rect) + radius, CGRectGetMaxY(rect) - radius, radius, M_PI / 2, M_PI, 0);
CGContextAddArc(context, CGRectGetMinX(rect) + radius, CGRectGetMinY(rect) + radius, radius, M_PI, 3 * M_PI / 2, 0);
CGContextClosePath(context);
CGContextFillPath(context);

Creating a UIImage from a rotated UIImageView

I have a UIImageView with an image in it. I have rotated the image prior to display by setting the transform property of the UIImageView to CGAffineTransformMakeRotation(angle) where angle is the angle in radians.
I want to be able to create another UIImage that corresponds to the rotated version that I can see in my view.
I am almost there, by rotating the image context I get a rotated image:
- (UIImage *) rotatedImageFromImageView: (UIImageView *) imageView
{
UIImage *rotatedImage;
// Get image width, height of the bounding rectangle
CGRect boundingRect = [self getBoundingRectAfterRotation: imageView.bounds byAngle:angle];
// Create a graphics context the size of the bounding rectangle
UIGraphicsBeginImageContext(boundingRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// Rotate and translate the context
CGAffineTransform ourTransform = CGAffineTransformIdentity;
ourTransform = CGAffineTransformConcat(ourTransform, CGAffineTransformMakeRotation(angle));
CGContextConcatCTM(context, ourTransform);
// Draw the image into the context
CGContextDrawImage(context, CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height), imageView.image.CGImage);
// Get an image from the context
rotatedImage = [UIImage imageWithCGImage: CGBitmapContextCreateImage(context)];
// Clean up
UIGraphicsEndImageContext();
return rotatedImage;
}
However the image is not rotated about its centre. I have tried all kinds of transforms concatenated with my rotate to get it to rotate around the centre but to no avail. Am I missing a trick? Is this even possible since I am rotating the context not the image?
Getting desperate to make this work now, so any help would be appreciated.
Dave
EDIT: I've been asked several times for my boundingRect code, so here it is:
- (CGRect) getBoundingRectAfterRotation: (CGRect) rectangle byAngle: (CGFloat) angleOfRotation {
// Calculate the width and height of the bounding rectangle using basic trig
CGFloat newWidth = rectangle.size.width * fabs(cosf(angleOfRotation)) + rectangle.size.height * fabs(sinf(angleOfRotation));
CGFloat newHeight = rectangle.size.height * fabs(cosf(angleOfRotation)) + rectangle.size.width * fabs(sinf(angleOfRotation));
// Calculate the position of the origin
CGFloat newX = rectangle.origin.x + ((rectangle.size.width - newWidth) / 2);
CGFloat newY = rectangle.origin.y + ((rectangle.size.height - newHeight) / 2);
// Return the rectangle
return CGRectMake(newX, newY, newWidth, newHeight);
}
OK - at last I seem to have done it. Any comments on the correctness would be useful... needed a translate, a rotate, a scale and an offset from the drawing rect position to make it work. Code is here:
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformTranslate(transform, boundingRect.size.width/2, boundingRect.size.height/2);
transform = CGAffineTransformRotate(transform, angle);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
CGContextConcatCTM(context, transform);
// Draw the image into the context
CGContextDrawImage(context, CGRectMake(-imageView.image.size.width/2, -imageView.image.size.height/2, imageView.image.size.width, imageView.image.size.height), imageView.image.CGImage);
// Get an image from the context
rotatedImage = [UIImage imageWithCGImage: CGBitmapContextCreateImage(context)];

Resources