How to XOR two images in Flutter - image

I have these two images
What I want to do is to xor them to get this image:
I have tried to do it using CustomPaint and setting BlendMode to XOR But it gives me a black screen
Here's the code I used:
class XorPainter extends CustomPainter {
#override
void paint(Canvas canvas, Size size) async {
if (imageA != null && imageB != null) {
canvas.drawImage(imageA, Offset.zero, Paint());
canvas.save();
canvas.drawImage(
imageB, Offset.zero, Paint()..blendMode = BlendMode.xor);
canvas.restore();
}
}
#override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
For more information: see this

I believe its more of a a misconception of the BlendMode.xor, what they do is just like a regular xor truth table where every pixel is either 0 (transparent) if both of them are some color or unaffected where both overlap if one of them is transparent in that same area, because of that you will always get a transparent black square (unless for example you make the apple image with a transparent background, in which case the second image will have an empty space with the shape of the apple in the middle). I think what you really wanted was difference or exlusion to have that negated effect
class XorPainter extends CustomPainter {
final ui.Image imageA;
final ui.Image imageB;
XorPainter(this.imageA, this.imageB);
#override
void paint(Canvas canvas, Size size) async {
canvas.drawImage(imageA, Offset.zero, Paint());
canvas.saveLayer(null, Paint()..blendMode = BlendMode.difference); // or BlendMode.exclusion
canvas.drawImage(imageB, Offset.zero, Paint());
canvas.restore();
}
#override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}

Related

Android - How to make google Maps display a polyline that animates sequenctial flashing dots

I am searching for a way to animate the dots between two markers on a google map in android device.
So what i want in the end is the following line between the two images:
and it would be used like this typical google polyline implementation:
lets say there is a point A and a Point B. if im directing the user to point B, then the line animates to from point A to point B so the user knows to walk in this direction.
to achieve this i thought i could get the points out of the polyLine and remove them and add them back
rapidily. so lets say i had 5 points in the polyLine, i would remove position 1 , then put it back, then remove position 2, and put it back, to simulate this animation.
but it does not work . once hte polyline is set it seems i cannot alter it. you have any suggestions ?
val dotPattern = Arrays.asList(Dot(), Gap(convertDpToPixel(7).toFloat()))
val polyLineOptions: PolylineOptions = PolylineOptions()
.add(usersLocation)
.add(users_destination)
.pattern(dotPattern)
.width(convertDpToPixel(6).toFloat())
dottedPolyLine = googleMap.addPolyline(polyLineOptions)
dottedPolyLine?.points?.removeAt(1) // here as a test if my idea i try removing a point but it looks like a point here means current location or destination so there always 2. i thought a point would be one of the dots.
You can use MapView-based custom view View Canvas animationlike in this answer:
This approach requires
MapView-based
custom
view,
that implements:
drawing over the MapView canvas;
customizing line styles (circles instead of a simple line);
binding path to Lat/Lon coordinates of map
performing animation.
Drawing over the MapView needs to override dispatchDraw().
Customizing line styles needs
setPathEffect()
method of
Paint
class that allows to create create path for "circle stamp" (in
pixels), which will repeated every "advance" (in pixels too),
something like that:
mCircleStampPath = new Path(); mCircleStampPath.addCircle(0,0,
CIRCLE_RADIUS, Path.Direction.CCW); mCircleStampPath.close();
For binding path on screen to Lat/Lon coordinates
Projection.toScreenLocation()
needed, that requires
GoogleMap
object so custom view should implements OnMapReadyCallback for
receive it. For continuous animation
postInvalidateDelayed()
can be used.
but not draw path directly from point A to point B, but from point A to point C that animated from A to B. To get current position of point C you can use SphericalUtil.interpolate() from Google Maps Android API Utility Library. Something like that:
public class EnhancedMapView extends MapView implements OnMapReadyCallback {
private static final float CIRCLE_RADIUS = 10;
private static final float CIRCLE_ADVANCE = 3.5f * CIRCLE_RADIUS; // spacing between each circle stamp
private static final int FRAMES_PER_SECOND = 30;
private static final int ANIMATION_DURATION = 10000;
private OnMapReadyCallback mMapReadyCallback;
private GoogleMap mGoogleMap;
private LatLng mPointA;
private LatLng mPointB;
private LatLng mPointC;
private float mCirclePhase = 0; // amount to offset before the first circle is stamped
private Path mCircleStampPath;
private Paint mPaintLine;
private final Path mPathFromAtoC = new Path();
private long mStartTime;
private long mElapsedTime;
public EnhancedMapView(#NonNull Context context) {
super(context);
init();
}
public EnhancedMapView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public EnhancedMapView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public EnhancedMapView(#NonNull Context context, #Nullable GoogleMapOptions options) {
super(context, options);
init();
}
#Override
public void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
canvas.save();
drawLineFomAtoB(canvas);
canvas.restore();
// perform one shot animation
mElapsedTime = System.currentTimeMillis() - mStartTime;
if (mElapsedTime < ANIMATION_DURATION) {
postInvalidateDelayed(1000 / FRAMES_PER_SECOND);
}
}
private void drawLineFomAtoB(Canvas canvas) {
if (mGoogleMap == null || mPointA == null || mPointB == null) {
return;
}
// interpolate current position
mPointC = SphericalUtil.interpolate(mPointA, mPointB, (float) mElapsedTime / (float)ANIMATION_DURATION);
final Projection mapProjection = mGoogleMap.getProjection();
final Point pointA = mapProjection.toScreenLocation(mPointA);
final Point pointC = mapProjection.toScreenLocation(mPointC);
mPathFromAtoC.rewind();
mPathFromAtoC.moveTo(pointC.x, pointC.y);
mPathFromAtoC.lineTo(pointA.x, pointA.y);
// change phase for circles shift
mCirclePhase = (mCirclePhase < CIRCLE_ADVANCE)
? mCirclePhase + 1.0f
: 0;
mPaintLine.setPathEffect(new PathDashPathEffect(mCircleStampPath, CIRCLE_ADVANCE, mCirclePhase, PathDashPathEffect.Style.ROTATE));
canvas.drawPath(mPathFromAtoC, mPaintLine);
}
private void init() {
setWillNotDraw(false);
mCircleStampPath = new Path();
mCircleStampPath.addCircle(0,0, CIRCLE_RADIUS, Path.Direction.CCW);
mCircleStampPath.close();
mPaintLine = new Paint();
mPaintLine.setColor(Color.BLACK);
mPaintLine.setStrokeWidth(1);
mPaintLine.setStyle(Paint.Style.STROKE);
mPaintLine.setPathEffect(new PathDashPathEffect(mCircleStampPath, CIRCLE_ADVANCE, mCirclePhase, PathDashPathEffect.Style.ROTATE));
// start animation
mStartTime = System.currentTimeMillis();
postInvalidate();
}
#Override
public void getMapAsync(OnMapReadyCallback callback) {
mMapReadyCallback = callback;
super.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
invalidate();
}
});
if (mMapReadyCallback != null) {
mMapReadyCallback.onMapReady(googleMap);
}
}
public void setPoints(LatLng pointA, LatLng pointB) {
mPointA = pointA;
mPointB = pointB;
}
}
NB! This is just idea, not full tested code.

JavaFX: Mapping pixels on screen to a 2D matrix

I'm making an animation in which I need to keep track of explored/unexplored pixels on the screen.Initially the screen is black colored,then as the node(a circle) moves(over defined path) the explored pixels are set to white.For doing this task(color change) I'm using Canvas class of JavaFX as background and painting the path using an object of GraphicsContext class(see the createPathAnimation method),now I want to update the int 2D matrix as 0-unexplored,1-explored.
How can I use the changed() function inside createPathAnimation to update my matrix as that function is updating the pixel color to white and I need to update the same set of explored pixels to 1 in my matrix?
sample translation
I'm trying to use the inbuilt function because even if I know the initial and final pixel coordinates,its not easy to determine which all pixels will be set while the circle moves between them(for ex along one of the diagonals),since circle is a like a blob of tiny squares on a pixel level.
My motive is to find the number of white colored pixels after a diagonal translation.
public void start(Stage primaryStage)throws Exception{
Pane root=new Pane();
Path path1=createPath();
canvas=new Canvas(800,600);
root.getChildren().addAll(path1,canvas);
primaryStage.setScene(new Scene(root,800,600,Color.BLACK));
primaryStage.show();
Animation animation1=createPathAnimation(path1,Duration.seconds(10));
pt.getChildren().addAll(animation1);
pt.play();
}
private Path createPath(){
Path path=new Path();
path.setStroke(Color.BLACK);
path.setStrokeWidth(10);
path.getElements().add(new MoveTo(400,300));
path.getElements().add(new LineTo(600,500));
return path;
}
public int a,b;
private Animation createPathAnimation(Path path,Duration duration){
GraphicsContext gc=canvas.getGraphicsContext2D();
Circle pen=new Circle(0,0,10);
PathTransition pathTransition=new PathTransition(duration,path,pen);
pathTransition.currentTimeProperty().addListener(new ChangeListener<Duration>(){
Location oldLocation = null;
/**
* Draw a line from the old location to the new location
*/
#Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
if( oldValue == Duration.ZERO)
return;
// get current location
double x = pen.getTranslateX();
double y = pen.getTranslateY();
// initialize the location
if( oldLocation == null) {
oldLocation = new Location();
oldLocation.x = x;
oldLocation.y = y;
return;
}
// draw line
gc.setStroke(Color.WHITE);
gc.setLineWidth(30);
gc.strokeLine(oldLocation.x, oldLocation.y, x, y);
// update old location with current one
oldLocation.x = x;
oldLocation.y = y;
}
});
return pathTransition;
}
public static class Location {
double x;
double y;

How to get smooth animation with KeyPress event in javaFX?

I am trying to implement LEFT RIGHT movement of a rectangle shape in JavaFX. Below is my code:
public void start(Stage primaryStage) throws Exception {
AnchorPane ancPane = new AnchorPane();
final Rectangle rect = new Rectangle();
rect.setHeight(50);
rect.setWidth(50);
ancPane.getChildren().add(rect);
Scene scene = new Scene(ancPane, 400, 200, Color.GREEN);
primaryStage.setScene(scene);
primaryStage.show();
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent keyEvent) {
System.out.println("hello");
if(keyEvent.getCode().toString() == "RIGHT"){
System.out.println("Move Right");
TranslateTransition translateTransitionRight = new TranslateTransition();
translateTransitionRight.setDuration(Duration.millis(200));
translateTransitionRight.setNode(rect);
translateTransitionRight.setFromX(rect.getTranslateX());
translateTransitionRight.setToX(rect.getTranslateX()+30);
translateTransitionRight.play();
}
if(keyEvent.getCode().toString() == "LEFT"){
System.out.println("Move Left");
TranslateTransition translateTransitionRight = new TranslateTransition();
translateTransitionRight.setDuration(Duration.millis(200));
translateTransitionRight.setNode(rect);
translateTransitionRight.setFromX(rect.getTranslateX());
translateTransitionRight.setToX(rect.getTranslateX()-30);
translateTransitionRight.play();
}
}
});
}
Here when I press either LEFT/RIGHT key continuously (i.e. I don't released the key, I hold it for some times) the rectangle moves but not continuously. It pauses for a small fraction of time just after animation started. After the pause the animation continues smoothly.
How can I get rid of this pausing of animation with KeyEvents?
I would use an AnimationTimer for moving the rectangle, and just update a property representing the velocity on key pressed or key released:
final Rectangle rect = ... ;
final double rectangleSpeed = 100 ; // pixels per second
final double minX = 0 ;
final double maxX = 800 ; // whatever the max value should be.. can use a property and bind to scene width if needed...
final DoubleProperty rectangleVelocity = new SimpleDoubleProperty();
final LongProperty lastUpdateTime = new SimpleLongProperty();
final AnimationTimer rectangleAnimation = new AnimationTimer() {
#Override
public void handle(long timestamp) {
if (lastUpdateTime.get() > 0) {
final double elapsedSeconds = (timestamp - lastUpdateTime.get()) / 1_000_000_000.0 ;
final double deltaX = elapsedSeconds * rectangleVelocity.get();
final double oldX = rect.getTranslateX();
final double newX = Math.max(minX, Math.min(maxX, oldX + deltaX));
rect.setTranslateX(newX);
}
lastUpdateTime.set(timestamp);
}
};
rectangleAnimation.start();
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode()==KeyCode.RIGHT) { // don't use toString here!!!
rectangleVelocity.set(rectangleSpeed);
} else if (event.getCode() == KeyCode.LEFT) {
rectangleVelocity.set(-rectangleSpeed);
}
}
});
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.RIGHT || event.getCode() == KeyCode.LEFT) {
rectangleVelocity.set(0);
}
}
});
UPDATE:
The AnimationTimer executes its handle method once each time a frame is rendered by the JavaFX mechanism. The long passed into the handle method is a timestamp of the render frame, in nanoseconds.
The way this works is that we keep track of the last update time. The handle(...) method computes the elapsed time since the last update, multiplies it by the rectangle's velocity, and updates the translateX of the rectangle by that amount. The AnimationTimer is always running, but initially the velocity is set to zero so the rectangle doesn't move.
The keyPressed handler simply changes the velocity: to a positive value if moving right and a negative value if moving left. The keyReleased handler sets the velocity back to zero.

Blackberry support multiple resolutions [duplicate]

This question already has answers here:
Supporting multiple screens - Blackberry
(2 answers)
Closed 8 years ago.
I need to design the UI for a blackberry app. This app should support multiple blackberry resolutions.
One way would be to check the screen_width and screen_height every time, and accordingly fetch images from the res folder. Is there any other more efficient, or a better method to do this? I will also need to do the same for font sizes, of text, according to screen size.
Please help me know the standard method to support multiple BB resolutions
You can try, what I have tried in my applications without any issues so far.
Step 1:
Create a separate package like com.your_app_name.uiconfig which will
contain an abstract class say ModelConfig and different classes for
different resolutions like class BB83xxConfig for resolution 320x240
(width x height), class BB95xxConfig for resolution 360 x 480 (width x
height).
Step 2:
ModelConfig class will provide the concrete implementation of the
methods that will be common to all irrespective of the screen
resolutions and the declaration of abstract methods whose concrete
implementation will be provided in the respective classes based on the
screen resolution.
Step 3: Make each and every class, that is implemented for particular resolution extend ModelConfig and provide concrete
implementation of methods as per requirement.
Step 4: Use singleton pattern to get the instance of ModelConfig, so that it is intantiated only once and that instance is used
throughout.
ModelConfig.java (Just a sample)
public abstract class ModelConfig {
private static ModelConfig modelConfig = null;
public static ModelConfig getConfig() {
if (modelConfig == null) {
if (DeviceInfo.getDeviceName().startsWith("83")) {
modelConfig = new BB83xxConfig();
} else if (DeviceInfo.getDeviceName().startsWith("85")) {
// 85xx also has 360 x 240 same as 83xx device
modelConfig = new BB83xxConfig();
} else if (DeviceInfo.getDeviceName().startsWith("89")) {
modelConfig = new BB89xxConfig();
} else if (DeviceInfo.getDeviceName().startsWith("90")) {
modelConfig = new BB90xxConfig();
} else if (DeviceInfo.getDeviceName().startsWith("95")) {
modelConfig = new BB95xxConfig();
} else if (DeviceInfo.getDeviceName().startsWith("96")) {
modelConfig = new BB96xxConfig();
} else if (DeviceInfo.getDeviceName().startsWith("97")) {
modelConfig = new BB97xxConfig();
} else if (DeviceInfo.getDeviceName().startsWith("99")) {
modelConfig = new BB99xxConfig();
} else if (DeviceInfo.getDeviceName().startsWith("98")) {
// 9800 also has 360 x 480 same as 95xx device
modelConfig = new BB95xxConfig();
}else {
modelConfig = new DefaultConfig();
}
}
return modelConfig;
}
// Font height for the default font used for the application.
public abstract int getApplicationFontHeight();
// Font height for the header label font.
public abstract int getHeaderLabelFontHeight();
// Height for the coloured background of Header.
public abstract int getHeaderBarHeight();
// Height for the individual row in the list.
public abstract int getCustomListRowHeight();
public abstract int getStandardButtonWidth();
public abstract int getStandardLabelWidth();
public abstract int getTitleFontHeight();
// get Background colour for Header.
public int getHeaderBackgroundColor() {
return 0x26406D;
}
// get Bitmap showing Right Arrow.
public Bitmap getBitmapRightArrow() {
return Bitmap.getBitmapResource("right_arrow.png");
}
// get Bitmap rounded black border for editfield.
public Bitmap getBitmapRoundedBorderEdit(){
return Bitmap.getBitmapResource("rounded_border_black.png");
}
// get Bitmap rounded gray border and white background.
public Bitmap getBtmpRoundedBorderBgrnd(){
return Bitmap.getBitmapResource("rounded_border_grey.png");
}
// get Bitmap rounded gray border and white background.
public Bitmap getBtmpTransparentBgrnd(){
return Bitmap.getBitmapResource("img_transparent_background.png");
}
// get Bitmap showing down Arrow.
public Bitmap getBitmapDownArrow(){
return Bitmap.getBitmapResource("down_arrow.png");
}
}
BB95xxConfig.java (just a sample)
/*
* Common resolution 360*480 pixels (width x height)
*/
public class BB95xxConfig extends ModelConfig {
// Font height for the default font used for the application.
// returns Desired height in pixels.
public int getApplicationFontHeight() {
return 18;
}
// Font height for the header label font.
// returns Desired height in pixels.
public int getHeaderLabelFontHeight() {
return 20;
}
// returns Desired height in pixels for the header background.
public int getHeaderBarHeight() {
return Display.getHeight() / 10;
}
public int getCustomListRowHeight() {
return 50;
}
public int getStandardButtonWidth() {
return 108;
}
public int getStandardLabelWidth() {
return 150;
}
public int getTitleFontHeight() {
return 11;
}
}

Java - drawing many images with Graphics.drawImage() and 2-screen buffer strategy distorts and cuts images

I am using a loop to invoke double buffering painting. This, together with overriding my only Panel's repaint method, is designed to pass complete control of repaint to my loop and only render when it necessary (i.e. some change was made in the GUI).
This is my rendering routine:
Log.write("renderer painting");
setNeedsRendering(false);
Graphics g = frame.getBufferStrategy().getDrawGraphics();
g.setFont(font);
g.setColor(Color.BLACK);
g.fillRect(0, 0, window.getWidth(),window.getHeight());
if(frame != null)
window.paint(g);
g.dispose();
frame.getBufferStrategy().show();
As you can see, it is pretty standard. I get the grpahics object from the buffer strategy (initialized to 2), make it all black and pass it to the paint method of my "window" object.
After window is done using the graphics object, I dispose of it and invoke show on the buffer strategy to display the contents of the virtual buffer.
It is important to note that window passes the graphics object to many other children components the populate the window and each one, in turn, uses the same instance of the graphics object to draw something onto the screen: text, shapes, or images.
My problem begins to show when the system is running and a large image is rendered. The image appears to be cut into seveeal pieces and drawn again and again (3-4 times) with different offsets inside of where the image is supposed to be rendered. See my attached images:
This is the original image:
alt text http://img109.imageshack.us/img109/8308/controller.png
This is what I get:
alt text http://img258.imageshack.us/img258/3248/probv.png
Note that in the second picture, I am rendering shapes over the picture - these are always at the correct position.
Any idea why this is happening?
If I save the image to file, as it is in memory, right before the call to g.drawImage(...) it is identical to the original.
Uh, you are using Swing ?
Normally Swing automatically renders the image, you can't switch it off. The repaint()
method is out of bounds because Swing has a very complicated rendering routine due to
method compatibility for AWT widgets and several optimizations, inclusive drawing only
when necessary !
If you want to use the High-Speed Drawing API, you use a component with a BufferStrategy
like JFrame and Window, use
setIgnoreRepaint(false);
to switch off Swing rendering, set up a drawing loop and paint the content itself.
Or you can use JOGL for OpenGL rendering. The method you are using seems completely
at odds with correct Java2D usage.
Here the correct use:
public final class FastDraw extends JFrame {
private static final transient double NANO = 1.0e-9;
private BufferStrategy bs;
private BufferedImage frontImg;
private BufferedImage backImg;
private int PIC_WIDTH,
PIC_HEIGHT;
private Timer timer;
public FastDraw() {
timer = new Timer(true);
JMenu menu = new JMenu("Dummy");
menu.add(new JMenuItem("Display me !"));
menu.add(new JMenuItem("Display me, too !"));
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setIgnoreRepaint(true);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
super.windowClosing(evt);
timer.cancel();
dispose();
System.exit(0);
}
});
try {
backImg = javax.imageio.ImageIO.read(new File("MyView"));
frontImg = javax.imageio.ImageIO.read(new File("MyView"));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
PIC_WIDTH = backImg.getWidth();
PIC_HEIGHT = backImg.getHeight();
setSize(PIC_WIDTH, PIC_HEIGHT);
createBufferStrategy(1); // Double buffering
bs = getBufferStrategy();
timer.schedule(new Drawer(),0,20);
}
public static void main(String[] args) {
new FastDraw();
}
private class Drawer extends TimerTask {
private VolatileImage img;
private int count = 0;
private double time = 0;
public void run() {
long begin = System.nanoTime();
Graphics2D g = (Graphics2D) bs.getDrawGraphics();
GraphicsConfiguration gc = g.getDeviceConfiguration();
if (img == null)
img = gc.createCompatibleVolatileImage(PIC_WIDTH, PIC_HEIGHT);
Graphics2D g2 = img.createGraphics();
// Zeichenschleife
do {
int valStatus = img.validate(gc);
if (valStatus == VolatileImage.IMAGE_OK)
g2.drawImage(backImg,0,0,null);
else {
g.drawImage(frontImg, 0, 0, null);
}
// volatile image is ready
g.drawImage(img,0,50,null);
bs.show();
} while (img.contentsLost());
time = NANO*(System.nanoTime()-begin);
count++;
if (count % 100 == 0)
System.out.println(1.0/time);
}
}

Resources