Erasing parts of a bitmap in EaselJS using destination-out compositing - easeljs

I'm having a bit of difficulty getting some functionality to work. I'm trying to create an eraser and erase parts of an image using easelJS. I've seen other people do this, but only erasing other graphics - and when I try to erase an image, I can't get anything to work. If I wanted to erase a bitmap instead of other graphics, is that possible?
I also tried to use the AlphaMaskFilter, but it's giving me the exact opposite of what I'm looking for (it's masking everything, and only revealing what I paint).
var c = createjs, stage, art;
var x, y, listener, color, hue=0;
stage = new c.Stage("test");
var testImg = new c.Bitmap("http://lorempixel.com/output/animals-q-c-640-480-5.jpg");
art = stage.addChild(testImg, new c.Shape());
art.cache(0,0,600,400);
stage.on("stagemousedown", startDraw, this);
function startDraw(evt) {
listener = stage.on("stagemousemove", draw, this);
stage.on("stagemouseup", endDraw, this);
color = c.Graphics.getHSL(hue+=85, 50, 50);
x = evt.stageX-0.001; // offset so we draw an initial dot
y = evt.stageY-0.001;
draw(evt); // draw the initial dot
}
function draw(evt) {
art.graphics.ss(20,1).s(color).mt(x,y).lt(evt.stageX, evt.stageY);
// the composite operation is the secret sauce.
// we'll either draw or erase what the user drew.
art.updateCache(erase.checked ? "destination-out" : "source-over");
art.graphics.clear();
x = evt.stageX;
y = evt.stageY;
stage.update();
}
function endDraw(evt) {
stage.off("stagemousemove", listener);
evt.remove();
}
http://jsfiddle.net/17xec9y5/8/

Your example is only affecting the Shape instance that you have cached. When you use multiple arguments in addChild(), it returns the last added item, so in your sample, the art variable just references the shape. So the image is just below the "painted area" that you are drawing to.
To fix this, create and cache a container instead. A few minor additions:
Once the image loads, update the cache one time (to apply the image).
Then remove the image so it is no longer applied every time you update the cache while drawing.
That's it!
Here is a fiddle:
http://jsfiddle.net/lannymcnie/17xec9y5/9/
Relevant Code:
// Listen for the image load
testImg.image.onload = function() {
cont.updateCache("source-over"); // Update cache once
cont.removeChild(testImg); // Remove image
stage.update(); // Draw the stage to see the image
}
// Create a sub-container that will hold the art and image
var cont = stage.addChild(new c.Container());
art = new c.Shape(); // Art is just the shape
cont.cache(0,0,600,400); // Cache the container instead
cont.addChild(testImg, art);
// Then, later update the container's cache (instead of the art)
cont.updateCache(erase.checked ? "destination-out" : "source-over");

Related

Unity 5: how to zoom and translate an object from a grid layout to the center of the screen

I'm trying to create a scroll grid view in which every cell object is tapable.
When a cell object is tapped I want to scale and traslate it to the center of the screen and render it above other cells.
I was able to make it tapable and scale it in its position. Now I want to move the cell object to the center of the screen and render it above other cells.
I've tried many solutions but none of them works.
This is my hierarchy:
This is the grid in normal state:
This is the grid when a cell was tapped:
I'm populating the grid from a C# script dynamically.
void Populate()
{
GameObject cardContainerInstance, cardInstance;
foreach (var c in cardsCollection.GetAll())
{
if (c.IsOwned)
{
cardContainerInstance = Instantiate(cardContainer, transform);
cardInstance = cardContainerInstance.transform.Find("Card").gameObject;
var cardManager = cardInstance.GetComponent<CardManager>();
cardManager.card = c;
cardManager.AddListener(this);
}
else
{
Instantiate(cardSlot, transform);
}
}
}
public void OnCardClick(GameObject cardObject, Card card)
{
Debug.Log("OnCardClick " + card.name);
if (openedCard != null) {
if (openedCard.Number == card.Number)
{
CloseCard(openedCardObject);
}
else
{
CloseCard(openedCardObject);
OpenCard(cardObject, card);
}
}
else
{
OpenCard(cardObject, card);
}
}
void OpenCard(GameObject cardObject, Card card)
{
//cardObject.GetComponent<Canvas>().sortingOrder = 1;
var animator = cardObject.GetComponent<Animator>();
animator.SetTrigger("Open");
openedCard = card;
openedCardObject = cardObject;
}
void CloseCard(GameObject cardObject)
{
var animator = cardObject.GetComponent<Animator>();
animator.SetTrigger("Close");
openedCard = null;
openedCardObject = null;
}
I can't figure out how to move the cell to the center and render it above others.
Note that all is animated using an animator attached to the object itself.
Could anyone help me please? Thank you very much!
EDIT: more details
All cell object have the following hierarchy:
where:
CardContainer is an empty object added to use animator on Card child object
Card is the object itself that has a script, a canvas renderer and an animator
StatsImage is the object that slide out when the card is tapped
Image is a calssic UIImage with Image script, Shadow script and canvas renderer
Other component are simple texts.
EDIT: fix in progress
Trying to apply this suggestions I was able to manage the rendering order (as you see on the image below) but it seems that prevent touch events to be detected on the game object.
I've added a GraphicsRaycaster too and now the bottom horizontal scroll view scrolls again but only if I click and drag a card.
Moreover, with the GraphicsRaycaster, the main grid card still are not clickable and it's possible to open the card only if it is behind the bottom panel (if I click on the red spot in the image below the card behind the panel receives che click)
This is the CardContainer at runtime(note that I'm attaching new Canvas and GraphicsRaycaster on the CardContainer, which is the "root" element):
You didn't clarify whether you are using a sprite renderer or some other method but here is an answer for each.
Sprite renderer:
this the simple one. In each sprite renderer, there is a variable called "sortingOrder" in script and "Order in layer" in the inspector. sprite renderer with sorting Orders that are higher is rendered first. All you would need to do is call:
cardObject.GetComponent<SpriteRenderer>().sortingOrder = 1;
when you click the card, and
cardObject.GetComponent<SpriteRenderer>().sortingOrder = 0;
when you unclick it. I hope that makes sense!
Other Method:
this one is a bit harder and I would suggest that you switch to sprite renderers and it will be much easier and more stable down the road, but I can understand if you have already written a lot of scripts and don't want to go back and change them.
Anyway, all you will need to do Is create two layers: cardLower and cardUpper. then create a new camera and call it topCamera. now under the top camera object in the inspector, change the culling mask (it's near the top) and make sure cardUpper is selected. then change the Clear flags (first one) to "Don't Clear" finally change the depth to 0 (if that doesn't work change it to -2). Now objects in the cardUpper will always be rendered above everything else. You can change the layer through script with
cardObject.layer = "cardUpper"
or
cardObject.layer = "cardLower"
I hope that helps!
Ok, so its pretty simple. So you are going to want to add another canvas component to the game object, and check the override sorting to true. Then use
cardObject.GetComponent<Canvas>().sortingOrder = 1;
to place it in the front and
cardObject.GetComponent<Canvas>().sortingOrder = 0;
to put it in the back.
you are also going to need to put a GraphicsRaycaster on to each of the cardObjects
Ignore my other answer about sprite renderers, they are not needed here

ImageJ: how to get Image inside GenericDialog to repaint?

In my ImageJ plugin I display a GenericDialog which has a bunch of images attached to it, like this:
// global:
ColorProcessor cp = new ColorProcessor(50, 50); // new ColorProcessor
ImagePlus ip;
public void run(ImageProcessor ip) {
GenericDialog gdiag = new GenericDialog("Foo"); // new Dialolg
gdiag.addDialogListener(this); // adding Listener
gdiag.addMessage("Lorem Ipsum"); // adding Message
gdiag.addSlider("Bar", 1, 360, 1); // adding Slider
Color c = new Color(r, g, b);
cp.setColor(tarColor);
cp.fill();
ip = new ImagePlus("fooimg", cp);
gdiag.addImage(ip);
gdiag.showDialog();
}
I keep a reference to the Colorprocessor and the ImagePlus. When the slider gets moved on the GenericDialog, my the dialogItemChanged() event fires. Here I change the Color on the Image:
public boolean dialogItemChanged(GenericDialog gd, AWTEvent event) {
float fooVal = (float) ((Scrollbar)(gd.getSliders().get(0))).getValue();
// calculating color based on fooVal ...
Color selColor = new Color(r, g, b);
cp.setColor(selColor);
cp.fill();
}
Now when I run this, the Color in the Image does not update. Only when I change the size of the dialog and move the border over the image, the color displays correctly.
How can I force the dialog to repaint?
I tried so many different updates & repaints, I am out of options.
Wayne Rasband added this capability in the 1.51b12 daily build of ImageJ; see his response on the ImageJ mailing list, where this question was cross-posted.

LIBGDX - Image Button - join images

I am trying to use de Image Button on LIBGDX to create a button based on two images.
Using add to second image, works fine, but have one problem.
The images are of different sizes.
Note: I am testing with the same picture to see the result
Is there a way to correct this? Using some scale to the images?
levelsTexture = new Texture(Gdx.files.internal("level1.png"));
levels = new TextureRegion(levelsTexture).split(TILE_WIDTH, TILE_HEIGHT);
ImageButton levels_image = new ImageButton(new TextureRegionDrawable(new
TextureRegion(levels[0][0])));
levels_image.add(new Image (levels[0][0]));
stage.addActor(levels_image);
levels_image.setScale(2f);
The problem:
ImageButton is an extension of the Table class and typically the ImageButton images are set as the background. Using the "add" method for the second image like you did might work kind of, but it behaves differently than setting the background and it also might not be what you want if you want the the second image to also change when you click the button.
The easiest way to add two images to a single ImageButton would be to simply combine the two images in Photoshop (or equivalent) and use that single image on the ImageButton.
The more advanced (and more flexible) method would be to combine the two images programmatically and use this as the background for your ImageButton. This can be done by creating a custom class which extends BaseDrawable and have it take two Images in the constructor. If you want your images stacked on top of each other, set the minHeight of your custom drawable class to be the combined height of your two images. Then override the draw method and draw your two images on top of each other like this:
#Override
public void draw(Batch batch, float x, float y, float width, float height){
img1.getDrawable().draw(batch, x, y, img1.getWidth(), img1.getHeight());
img2.getDrawable().draw(batch, x, y+img1.getHeight(), img2.getWidth(), img2.getHeight());
}
}
The ImageButton takes a Drawable in its constructor, so you can pass this object right into the button when you create it and both of your Images should appear in the button and they will be treated as one.
I've done something similar to make a background for a table using multiple Images and this method works great.
I wrote my own SpriteButton class in which I implement this method for scaling my textures.
private Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
int original_width = imgSize.width;
int original_height = imgSize.height;
int bound_width = boundary.width;
int bound_height = boundary.height;
int new_width = original_width;
int new_height = original_height;
// first check if we need to scale width
if (original_width > bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}
// then check if we need to scale even with the new height
if (new_height > bound_height) {
//scale height to fit instead
new_height = bound_height;
//scale width to maintain aspect ratio
new_width = (new_height * original_width) / original_height;
}
return new Dimension(new_width, new_height);
}
Then finally you draw the texture with the output dimension as as size to draw.
sb.begin();
sb.draw(this.texture2, this.x, this.y, dim_size_new.width, dim_size_new.height);
sb.end();
So you could technically draw the second image to the size of the the first image, if the first image size is correct.
Your implementation will look different from mine but you should be able to figure it out form here on out.

remove graphics from inside a class as3

When I click a button in my game it draws shapes using the graphics in as3. simple shapes such as circles and rectangles.
I want to remove the graphics that have been drawn when something happens in one of my classes.
Basically when there is a hitTestObject (which works fine) I want all graphics on stage to be cleared.
if (gb2.hitTestObject(h1s2))
{
trace ("holed")
ySpeed2=0;
xSpeed2=0;
this.visible=false;
var mcSplash:MovieClip =parent.getChildByName("mcSplash") as MovieClip;
mcSplash.visible=true;
//parent.drawings.graphics.clear();
}
My attempt using parent.drawings.graphics.clear(); was unsuccessful, it gives me this error:
Line 481 1119: Access of possibly undefined property drawings through a reference with static type flash.display:DisplayObjectContainer.
Anyone have any suggestions
UPDATE:
this is how, on the min time line, the drawings occur.
var drawings:Shape = new Shape;
for (i=0; i<numRecs; i++)
{
recStartX = Number(xmlContent.rec[i].startpoint.#ptx);
recStartY = Number(xmlContent.rec[i].startpoint.#pty);
recWidth = Number(xmlContent.rec[i].dimensions.#w);
recHeight = Number(xmlContent.rec[i].dimensions.#h);
fillColor=int(xmlContent.rec[i].look.fillhex);
lineThick = Number(xmlContent.rec[i].look.strokethick);
lineColor = int(xmlContent.rec[i].look.strokehex);
drawings.graphics.lineStyle(lineThick, lineColor);
drawings.graphics.beginFill(fillColor);
drawings.graphics.drawRect(recStartX,recStartY,recWidth,recHeight);
drawings.graphics.endFill();
}
Create an array and push in each shape/rect.
Then iterate through this and remove..
for(var iteration:int = 0; iteration < rectArray.length; iteration++)
this.removeChild(rectArray[iteration]);
or if you are calling this from a class, use
MovieClip(this.root).removeChild(rectArray[iteration]);
Hopefully this is helpful :)
Z
What's drawings?! If you draw in mcSplash, you should use mcSplash.graphics.clear(). If you draw in a child called drawings, you should first get it as a child (after mcSplash get): var drawings = mcSplash.getChildByName('drawings); drawings.graphics.clear();. You could write checks to see what's going on: if (mcSlpash) { if (drawings) {, etc..

Can I use icons with RGBA transparency when using GTK+ drag and drop?

I am in the process of adding drag and drop support to an existing Mono/C#/GTK# application. I was wondering whether it was possible to use RGBA transparency on the icons that appear under the mouse pointer when I start dragging an object.
So far, I realized the following:
I can set the bitmap in question by calling the Gtk.Drag.SourceSetIconPixbuf() method. However, no luck with alpha transparency: pixels that are not fully opaque would get 100% transparent this way.
I also tried calling RenderPixmapAndMask() on the GdkPixbuf so that I could use Gtk.Drag.SourceSetIcon() with an RGBA colormap of my Screen. It didn't work either: whenever I started dragging, I got the following error:
[Gdk] IA__gdk_window_set_back_pixmap: assertion 'pixmap == NULL || gdk_drawable_get_depth (window) == gdk_drawable_get_depth (pixmap)' failed.
This way, the pixmap doesn't even get copied, only a white shape (presumably set by the mask argument of SetSourceIcon()) shows up on dragging.
I'd like to ask if there's a way to make these icons have alpha transparency, despite the fact that I failed to do so. In case it's impossible, answers discussing the reasons of the lack of this feature would also be helpful. Thank you.
(Compositing is - of course - enabled on my desktop (Ubuntu/10.10, Compiz/0.8.6-0ubuntu9).)
Ok, finally I solved it. You should create a new Gtk.Window of POPUP type, set its Colormap to your screen's RGBA colormap, have the background erased by Cairo to a transparent color, draw whatever you'd like on it and finally pass it on to Gtk.Drag.SetIconWidget().
Sample code (presumably you'll want to use this inside OnDragBegin, or at a point where you have a valid drag context to be passed to SetIconWidget()):
Gtk.Window window = new Gtk.Window (Gtk.WindowType.Popup);
window.Colormap = window.Screen.RgbaColormap;
window.AppPaintable = true;
window.Decorated = false;
window.Resize (/* specify width, height */);
/* The cairo context can only be created when the window is being drawn by the
* window manager, so wrap drawing code into an ExposeEvent delegate. */
window.ExposeEvent += delegate {
Context ctx = Gdk.CairoHelper.Create (window.GdkWindow);
/* Erase the background */
ctx.SetSourceRGBA (0, 0, 0, 0);
ctx.Operator = Operator.Source;
ctx.Paint ();
/* Draw whatever you'd like to here, and then clean up by calling
Dispose() on the context's target. */
(ctx.Target as IDisposable).Dispose ();
};
Gtk.Drag.SetIconWidget(drag_context, window, 10, 10);