I'm using Processing, and I have a method ( smooth()
here) that I would like to use for PApplet
object when I draw in the window and for PGraphics
when I draw in a image.
The problem is, theses two classes ( PApplet
& PGraphics
) extends only from the Object
class and Eclipse said I must choice between the PApplet
cast or the PGraphics
cast but i want to use both in this case.
How can I fix that ?
There isn't a magical way to support two completely different types. There are a couple workarounds though.
You could use overloading which means creating separate functions for each type. Something like this:
void drawRect(PGraphics pg){
pg.rect(1, 2, 3, 4);
}
void drawRect(PApplet p){
p.rect(1, 2, 3, 4);
}
Or you could rely on the fact that the PApplet
class has a g
variable that references its internal PGraphics
instance. Then you'd only need one function that takes a PGraphics
and pass in the g
variable when you had a PApplet
instance. Something like this:
void setup(){
size(500, 500);
}
void draw(){
drawCircle(g);
}
void drawCircle(PGraphics pg){
pg.ellipse(mouseX, mouseY, 20, 20);
}
This approach is a bit hacky, so an even better solution would be to refactor your PApplet
code so it always draws to a PGraphics
explicitly. Then you could pass that PGraphics
instance to your function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.