ios - Choosing a random point within a circular image in a UIImageView -


i have app color wheel , i'm trying pick random color within color wheel. however, i'm having problems verifying random point falls within color wheel.

here's code is:

cgpoint randompoint = cgpointmake(arc4random() % (int)colorwheel.bounds.size.width, arc4random() % (int)colorwheel.bounds.size.height); uicolor *randomcolor = [self colorofpoint:randompoint];  cgpoint pointinview = [colorwheel convertpoint:randompoint fromview:colorwheel.window]; if (cgrectcontainspoint(colorwheel.bounds, pointinview)) {     nslog(@"%@", randomcolor); } else {     nslog(@"out of bounds"); } 

a couple of other methods of verifying point i've tried no luck:

if (cgrectcontainspoint(colorwheel.frame, randompoint)) {  nslog(@"%@", randomcolor);  }  if ([colorwheel pointinside:[self.view convertpoint:randompoint toview: colorwheel] withevent: nil]) {     nslog(@"%@", randomcolor); } 

sometimes it'll output "out of bounds", , it'll output color white (the background around color wheel white there's no white in color wheel image).

the color wheel image circle, i'm not sure if that's throwing off test, although seems white pops way transparent square outline around image giving white color.

if want generate random point in circle, better pick point in polar coordinates , convert cartesian.

the polar coordinate space uses 2 dimesions, radius , angle. radius distance center, , angle starts @ "due east" 0, , goes around counter-clockwise 2π (that's in radians, 360˚ of course in degrees).

presumably wheel divided simple wedges, radius doesn't matter; need pick random angle.

uint32_t angle = arc4random_uniform(360); // radius halfway center edge. // assumes circle enclosed, i.e., diameter == width cgfloat radius = colorwheel.bounds.size.width / 4; 

this function give cartesian point polar coordinates. wikipedia explains simple math if you're interested.

/** convert polar point (radius, theta) cartesian (x,y). */ cgpoint poltocar(cgfloat radius, cgfloat theta) {     return (cgpoint){radius * cos(theta), radius * sin(theta)}; } 

the function uses radians theta, because sin() , cos() do, change angle radians, , can convert:

cgfloat theta = (angle * m_pi) / 180.0 cgpoint randompoint = poltocar(radius, theta); 

one last step: circle has origin @ same place view, is, in corner, need translate point use center origin.

cgpoint addpoints(cgpoint lhs, cgpoint rhs) {     return (cgpoint){lhs.x + rhs.x, lhs.y, rhs.y}; }  cgpoint offset = (cgpoint){colorwheel.bounds.size.width / 2,                            colorwheel.bounds.size.height / 2};  randompoint = addpoints(randompoint, offset); 

and new randompoint within circle.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -