Android Toast in iPhone? - android

When I write Android apps, I love the Toast feature. Is there a way to get this kind of set and forget popup message in iPhone development using MonoTouch (C# .NET)?

MonoTouch Toast Version here. Inspired by Android.
To call it,
ToastView t = new ToastView ("Email Sent", 1000);
t.Show ();
Enum File:
public enum ToastGravity
{
Top = 0,
Bottom = 1,
Center = 2
}
ToastSettings File:
using System;
using System.Drawing;
using MonoTouch.UIKit;
namespace General
{
public class ToastSettings
{
public ToastSettings ()
{
this.Duration = 500;
this.Gravity = ToastGravity.Center;
}
public int Duration
{
get;
set;
}
public double DurationSeconds
{
get { return (double) Duration/1000 ;}
}
public ToastGravity Gravity
{
get;
set;
}
public PointF Position
{
get;
set;
}
}
}
Main Toast Class:
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.ObjCRuntime;
namespace General
{
public class ToastView : NSObject
{
ToastSettings theSettings = new ToastSettings ();
private string text = null;
UIView view;
public ToastView (string Text, int durationMilliseonds)
{
text = Text;
theSettings.Duration = durationMilliseonds;
}
int offsetLeft = 0;
int offsetTop = 0;
public ToastView SetGravity (ToastGravity gravity, int OffSetLeft, int OffSetTop)
{
theSettings.Gravity = gravity;
offsetLeft = OffSetLeft;
offsetTop = OffSetTop;
return this;
}
public ToastView SetPosition (PointF Position)
{
theSettings.Position = Position;
return this;
}
public void Show ()
{
UIButton v = UIButton.FromType (UIButtonType.Custom);
view = v;
UIFont font = UIFont.SystemFontOfSize (16);
SizeF textSize = view.StringSize (text, font, new SizeF (280, 60));
UILabel label = new UILabel (new RectangleF (0, 0, textSize.Width + 5, textSize.Height + 5));
label.BackgroundColor = UIColor.Clear;
label.TextColor = UIColor.White;
label.Font = font;
label.Text = text;
label.Lines = 0;
label.ShadowColor = UIColor.DarkGray;
label.ShadowOffset = new SizeF (1, 1);
v.Frame = new RectangleF (0, 0, textSize.Width + 10, textSize.Height + 10);
label.Center = new PointF (v.Frame.Size.Width / 2, v.Frame.Height / 2);
v.AddSubview (label);
v.BackgroundColor = UIColor.FromRGBA (0, 0, 0, 0.7f);
v.Layer.CornerRadius = 5;
UIWindow window = UIApplication.SharedApplication.Windows[0];
PointF point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height / 2);
if (theSettings.Gravity == ToastGravity.Top)
{
point = new PointF (window.Frame.Size.Width / 2, 45);
}
else if (theSettings.Gravity == ToastGravity.Bottom)
{
point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height - 45);
}
else if (theSettings.Gravity == ToastGravity.Center)
{
point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height / 2);
}
else
{
point = theSettings.Position;
}
point = new PointF (point.X + offsetLeft, point.Y + offsetTop);
v.Center = point;
window.AddSubview (v);
v.AllTouchEvents += delegate { HideToast (null); };
NSTimer.CreateScheduledTimer (theSettings.DurationSeconds, HideToast);
}
void HideToast ()
{
UIView.BeginAnimations ("");
view.Alpha = 0;
UIView.CommitAnimations ();
}
void RemoveToast ()
{
view.RemoveFromSuperview ();
}
}
}

Check this out:
https://github.com/ecstasy2/toast-notifications-ios
Edit: The project has moved to github so i update the link.

Here's my version: http://github.com/scalessec/toast
I think it's simpler to use because it's implemented as a obj-c category, thereby adding the makeToast methods to any instance of UIView. eg:
[self.view makeToast:#"This is some message as toast."
duration:3.0
position:#"bottom"];

Are you looking for something like UIAlertView?

You can use this link for objective-c code for Toast
http://code.google.com/p/toast-notifications-ios/source/browse/trunk/
While this link for its usage
http://code.google.com/p/toast-notifications-ios/wiki/HowToUse
which could be like any one of the below samples
[[iToast makeText:NSLocalizedString(#"The activity has been successfully saved.", #"")] show];
[[[iToast makeText:NSLocalizedString(#"The activity has been successfully saved.", #"")]
setGravity:iToastGravityBottom] show];
[[[[iToast makeText:NSLocalizedString(#"Something to display a very long time", #"")]
etGravity:iToastGravityBottom] setDuration:iToastDurationLong] show];

You might be after Local Notifications, pretty sure they allow you to set a time, I think in epoch time to be fired off. Don't think there is a way to hide them though. I might be misunderstanding your question though cause I'm unfamiliar with Toast.

Just You can use the following code with uilabel and uianimation to get toast like in android.
It does two works one is toast task and it increases the height of the label according to the text length with wordwrap IOS 7 later link here
CGRect initialFrame = CGRectMake(20, self.view.frame.size.height/2,300, 40);
NSString *message=#"Toast in Iphone as in Android";
UILabel *flashLabel=[[UILabel alloc] initWithFrame:initialFrame];
flashLabel.font=[UIFont fontWithName:#"Optima-Italic" size:12.0];
flashLabel.backgroundColor=[UIColor whiteColor];
flashLabel.layer.cornerRadius=3.0f;
flashLabel.numberOfLines=0;
flashLabel.textAlignment=NSTextAlignmentCenter;
CGSize maxSize = CGSizeMake(flashLabel.frame.size.width, MAXFLOAT);
CGRect labelRect = [message boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:flashLabel.font} context:nil];
//adjust the label the the new height.
CGRect newFrame = flashLabel.frame;
newFrame.size.height = labelRect.size.height;
flashLabel.frame = newFrame;
flashLabel.text=message;
[self.view addSubview:flashLabel];
flashLabel.alpha=1.0;
self.view.userInteractionEnabled=FALSE;
[UIView animateWithDuration:13.0 animations:^
{
flashLabel.alpha=0.0f;
}
completion:^(BOOL finished)
{
self.view.userInteractionEnabled=TRUE;
[flashLabel removeFromSuperview];
}];

I modified John's answer as follows:
Toast.h
#interface Toast : NSObject
+ (void)toast:(NSString *)message
:(UIView *) view
:(int)delay;
#end
Toast.m
#import "Toast.h"
#interface Toast ()
#end
#implementation Toast
+ (void)toast:(NSString *)message
:(UIView *) view
:(int)delay
{
CGRect initialFrame = CGRectMake(10, view.frame.size.height/2, 300, 40);
UILabel *flashLabel=[[UILabel alloc] initWithFrame:initialFrame];
flashLabel.font=[UIFont fontWithName:#"Optima-Italic" size:19.0];
flashLabel.backgroundColor=[UIColor whiteColor];
flashLabel.layer.cornerRadius=9.0f;
flashLabel.clipsToBounds = YES;
flashLabel.numberOfLines=3;
flashLabel.textAlignment=NSTextAlignmentCenter;
CGSize maxSize = CGSizeMake(flashLabel.frame.size.width, MAXFLOAT);
CGRect labelRect = [message boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:flashLabel.font}
context:nil];
//adjust the label the the new height.
CGRect newFrame = flashLabel.frame;
newFrame.size.height = labelRect.size.height * 2;
flashLabel.frame = newFrame;
flashLabel.text=message;
[view addSubview:flashLabel];
flashLabel.alpha=1.0;
view.userInteractionEnabled=FALSE;
[UIView animateWithDuration:delay animations:^
{
flashLabel.alpha=0.0f;
}
completion:^(BOOL finished)
{
view.userInteractionEnabled=TRUE;
[flashLabel removeFromSuperview];
}];
}
#end

I have added a little modification to the toast class that handles rotation of the display.
public void Show ()
{
UIButton v = UIButton.FromType (UIButtonType.Custom);
view = v;
UIFont font = UIFont.SystemFontOfSize (16);
SizeF textSize = view.StringSize (text, font, new SizeF (280, 60));
UILabel label = new UILabel (new RectangleF (0, 0, textSize.Width + 5, textSize.Height + 5));
label.BackgroundColor = UIColor.Clear;
label.TextColor = UIColor.White;
label.Font = font;
label.Text = text;
label.Lines = 0;
label.ShadowColor = UIColor.DarkGray;
label.ShadowOffset = new SizeF (1, 1);
v.Frame = new RectangleF (0, 0, textSize.Width + 10, textSize.Height + 10);
label.Center = new PointF (v.Frame.Size.Width / 2, v.Frame.Height / 2);
v.AddSubview (label);
v.BackgroundColor = UIColor.FromRGBA (0, 0, 0, 0.7f);
v.Layer.CornerRadius = 5;
UIWindow window = UIApplication.SharedApplication.Windows[0];
PointF point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height / 2);
if (theSettings.Gravity == ToastGravity.Top)
{
point = new PointF (window.Frame.Size.Width / 2, 45);
}
else if (theSettings.Gravity == ToastGravity.Bottom)
{
point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height - 45);
}
else if (theSettings.Gravity == ToastGravity.Center)
{
point = new PointF (window.Frame.Size.Width / 2, window.Frame.Size.Height / 2);
}
else
{
point = theSettings.Position;
}
point = new PointF (point.X + offsetLeft, point.Y + offsetTop);
v.Center = point;
//handle screen rotation
float orientation=0;
switch(UIApplication.SharedApplication.StatusBarOrientation)
{
case UIInterfaceOrientation.LandscapeLeft:
orientation=-90;
break;
case UIInterfaceOrientation.LandscapeRight:
orientation=90;
break;
case UIInterfaceOrientation.PortraitUpsideDown:
orientation=180;
break;
}
v.Transform=CGAffineTransform.MakeRotation ((float)(orientation / 180f * Math.Pi));
window.AddSubview (v);
v.AllTouchEvents += delegate { HideToast (); };
NSTimer.CreateScheduledTimer (theSettings.DurationSeconds, HideToast);
}

You could try my open source library TSMessages: https://github.com/toursprung/TSMessages
It's really easy to use and looks beautiful on iOS 5/6 and on iOS 7 as well.

I really like MonoTouch solution proposed by Bahai.
The following is not a substitution. Is just a ready-to-go one method the worked for me.
private async Task ShowToast(string message, UIAlertView toast = null)
{
if (null == toast)
{
toast = new UIAlertView(null, message, null, null, null);
toast.Show();
await Task.Delay(2000);
await ShowToast(message, toast);
return;
}
UIView.BeginAnimations("");
toast.Alpha = 0;
UIView.CommitAnimations();
toast.DismissWithClickedButtonIndex(0, true);
}
If the method is called from a background thread (not the main UI thread) then BeginInvokeOnMainThread is required which means just call it like this.
BeginInvokeOnMainThread(() =>
{
ShowToast(message);
});

I created a new repo on github with a class to do iOS toast-style alerts. I didn't like the one on code.google.com, it didn't rotate properly and wasn't pretty.
https://github.com/esilverberg/ios-toast
Enjoy folks.

Related

Android - PDFTron - draw annotation in zoom in mode

I'm using the PdfTron SDK and i'm trying to draw annotation after the user doing zoom in, the annotation need to be in the side of the book (the third pic) but when we do zoom in it's drawing in the center of the book (pic 1 and 2).
Example with zoom (the wrong state):
Example without zoom (the right state):
right now i'm using the function convPagePtToScreenPt but it's drawing the annotation properly just if the user doesn't making zoom in.
Does somebody knows in which function is suppose to use?
This is my code :
public synchronized void drawAnnotation(AnnotationData annotationData){
if (annotationData == null) {
return;
}
AnnotationType annotationType = annotationData.getType();
if (annotationType == null) {
return;
}
ToolManager.Tool tool = mToolManager.createTool(ToolManager.e_text_annot_create, null);
if (tool instanceof StickyNoteCreate) {
StickyNoteCreate annotStickyCreate = (StickyNoteCreate) tool;
Point point;
double[] pts;
double[] ptsForScreenSize = {0, 0};
int orientation = mContext.getResources().getConfiguration().orientation;
if (mPDFView != null) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
ptsForScreenSize = mPDFView.convScreenPtToPagePt((double) BookReader.SCREEN_WIDTH, (double) BookReader.SCREEN_HEIGHT, annotationData.getPage());
} else {
ptsForScreenSize = mPDFView.convScreenPtToPagePt((double) BookReader.SCREEN_HEIGHT, (double) BookReader.SCREEN_WIDTH, annotationData.getPage());
if (!TextUtils.isEmpty(annotationData.getStartLoc()) && !TextUtils.isEmpty(annotationData.getEndLoc()) && mPDFView != null) {
//if we have an annotation for text
pts = mPDFView.convPagePtToScreenPt(annotationData.getStartX(), annotationData.getStartY(), annotationData.getPage());
} else {
//if we have an annotation for Page
pts = new double[]{0, 0};
}
ptsForScreenSize = mPDFView.convPagePtToScreenPt(ptsForScreenSize[0] - INT_ANNO_PADDING, ptsForScreenSize[1], annotationData.getPage());
final AnnotationData noteTextHighlight = new AnnotationData(annotationData);
//we don't need to set UniqueId for this highlight annotation
noteTextHighlight.setUniqueId(null);
highlightSelectedText(noteTextHighlight);
double marginY = BookReader.SCREEN_HEIGHT * 0.015;
point = new Point(ptsForScreenSize[0], pts[1] + marginY);
annotStickyCreate.createNoteIconOnPage(annotationData, point);
}
}
}
}
public void createNoteIconOnPage(AnnotationData annotationData, Point noteIconPoint) {
KsLog.d("IsBookReaderAviliable","createNoteIconOnPage : " + BookReader.isBookReaderVisible());
if(BookReader.isBookReaderVisible()){
try {
mPDFView.docLock(true);
PDFDoc pdfDoc = mPDFView.getDoc();
double[] pts = mPDFView.convScreenPtToPagePt(noteIconPoint.x, noteIconPoint.y, annotationData.getPage());
Point p = new Point(pts[0], pts[1]);
com.pdftron.pdf.annots.Text text = com.pdftron.pdf.annots.Text.create(pdfDoc, p);
text.setUniqueID(annotationData.getUniqueId());
//creating the annotation appearance - icon
// Let's create an appearance for the annotation using an image
ElementBuilder builder = new ElementBuilder();
ElementWriter writer = new ElementWriter();
writer.begin(pdfDoc);
Image image = Image.create(pdfDoc, annotationData.getDrawable());
int w = image.getImageWidth(), h = image.getImageHeight();
Element element = builder.createImage(image, 0, 0, w, h);
writer.writePlacedElement(element);
writer.writeElement(builder.createTextBegin(Font.create(pdfDoc, Font.e_times_roman), 12));
writer.writeElement(element);
writer.writeElement(builder.createTextEnd());
Obj appearance = writer.end();
appearance.putRect("BBox", 0.1, 0.1, w, h);
text.setAppearance(appearance);
/*
The left icons spouse to be bigger the the regular icons
*/
if (annotationData.getType() == AnnotationData.AnnotationType.LINK && (annotationData.getShard() == AnnotationData.LEFT_LINK_A || annotationData.getShard() == AnnotationData.LEFT_LINK_B)) {
text.setRect(new Rect(pts[0], pts[1], pts[0] + 30, pts[1] + 30));
}
if (annotationData.getType() == AnnotationData.AnnotationType.NOTE) {
text.setContents(AnnotationData.NOTE_TYPE_CONTENTS);
} else if (annotationData.getType() == AnnotationData.AnnotationType.LINK) {
text.setContents(AnnotationData.LINK_TYPE_CONTENTS);
}
KsLog.d("createNoteIconOnPage","getPage() " + annotationData.getPage());
Page page = pdfDoc.getPage(annotationData.getPage());
if (page != null) {
page.annotPushBack(text);
}
mAnnotPushedBack = true;
mAnnot = text;
mAnnotPageNum = annotationData.getPage();
KsLog.d("createNoteIconOnPage","mDownPageNum " + mAnnotPageNum);
buildAnnotBBox();
mPDFView.update(mAnnot, mAnnotPageNum);
raiseAnnotationAddedEvent(mAnnot, mAnnotPageNum);
} catch (Exception ex) {
Log.e(PDFTronReader.TAG, ex.toString());
mNextToolMode = ToolManager.e_pan;
} finally {
mPDFView.docUnlock();
}
mPDFView.waitForRendering();
}
}
The following code will place an annotation on the right side of any page, 1 inch from the top.
Matrix2D mtx = page.getDefaultMatrix(true).inverse();
double x1 = page.getPageWidth() - 25; // this is the width as the a user sees it (rotated). 20 is the width of a Text annotation
double y1 = 72; // not clear how you decide the vertical placement. In this example, this 1 inch from the top as the user views the page. If you have the value from the bottom, switch the boolean value argument in GetDefaultMatrix
mtx.mult(ref x1, ref y1);
com.pdftron.pdf.Annots.Text txt = com.pdftron.pdf.Text.create(doc, new Point(x1, y1));
page.annotPushBack(txt);
Regarding your code, there appeared to be confusion over Screen and Page coordinates. For example, for ptsForScreenSize on one line of you pass in the results of ConvScreenPtToPagePt, and in another line, you pass in the results of ConvPagePtToScreenPt.

Android: Shape detection with JavaCV

I am new to JavaCV. I am trying to detect largest rectangle in image and outline it with color over original image. I am posting code below which I have tried but it is not working. I am getting edgeDetectedImage properly. I am getting 4 corner points properly. Just cvDrawLine is not working. Please Help if I am missing anything:
OnClick of button I am processing image and showing it again on ImageView.
In onClickListener of button:
if ((new File(path + "trial.jpg")).exists()) {
opencv_core.IplImage originalImage = opencv_imgcodecs.cvLoadImage(path + "trial.jpg", opencv_imgcodecs.CV_IMWRITE_JPEG_QUALITY);
opencv_core.IplImage iplImage = opencv_imgcodecs.cvLoadImage(path + "trial.jpg", opencv_imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);
opencv_core.IplImage edgeDetectedImage = applyCannyRectangleEdgeDetection(iplImage, 80);
opencv_core.CvSeq largestContour = findLargestContour(edgeDetectedImage);
opencv_core.CvPoint[] cvPoints = new opencv_core.CvPoint[4];
for(int i=0; i<largestContour.total();i++)
{
opencv_core.CvPoint cvPoint = new opencv_core.CvPoint(cvGetSeqElem(largestContour, i));
cvPoints[i] = cvPoint;
}
cvDrawLine(originalImage, cvPoints[0], cvPoints[1], opencv_core.CvScalar.YELLOW, 10, 10, 10);
cvDrawLine(originalImage, cvPoints[1], cvPoints[2], opencv_core.CvScalar.YELLOW, 10, 10, 10);
cvDrawLine(originalImage, cvPoints[2], cvPoints[3], opencv_core.CvScalar.YELLOW, 10,10, 10);
cvDrawLine(originalImage, cvPoints[3], cvPoints[0], opencv_core.CvScalar.YELLOW, 10, 10,10);
opencv_imgcodecs.cvSaveImage(path + "img1.jpg", originalImage);
if ((new File(path + "img1.jpg").exists())) {
imageView.setImageDrawable(Drawable.createFromPath(path + "img1.jpg"));
}
}
Method applyCannyRectangleEdgeDetection(IplImage, int):
private opencv_core.IplImage applyCannyRectangleEdgeDetection(opencv_core.IplImage iplImage, int percent) {
opencv_core.IplImage destImage = downScaleImage(iplImage, percent);
OpenCVFrameConverter.ToMat converterToMat = new OpenCVFrameConverter.ToMat();
Frame grayImageFrame = converterToMat.convert(destImage);
opencv_core.Mat grayImageMat = converterToMat.convertToMat(grayImageFrame);
GaussianBlur(grayImageMat, grayImageMat, new opencv_core.Size(5, 5), 0.0, 0.0, BORDER_DEFAULT);
destImage = converterToMat.convertToIplImage(grayImageFrame);
cvErode(destImage, destImage);
cvDilate(destImage, destImage);
cvCanny(destImage, destImage, 20, 55);
return destImage;
}
Method downScaleImage(IplImage, int)
private opencv_core.IplImage downScaleImage(opencv_core.IplImage srcImage, int percent) {
opencv_core.IplImage destImage = cvCreateImage(cvSize((srcImage.width() * percent) / 100, (srcImage.height() * percent) / 100), srcImage.depth(), srcImage.nChannels());
cvResize(srcImage, destImage);
return destImage;
}
Method findLargestContour(IplImage)
private opencv_core.CvSeq findLargestContour(opencv_core.IplImage edgeDetectedImage) {
opencv_core.IplImage foundContoursOfImage = cvCloneImage(edgeDetectedImage);
opencv_core.CvMemStorage memory = new opencv_core.CvMemStorage().create();
opencv_core.CvSeq contours = new opencv_core.CvSeq();
cvFindContours(foundContoursOfImage, memory, contours, Loader.sizeof(opencv_core.CvContour.class), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, new opencv_core.CvPoint(0, 0));
int maxWidth = 0;
int maxHeight = 0;
opencv_core.CvRect contr = null;
opencv_core.CvSeq seqFound = null;
opencv_core.CvSeq nextSeq;
for (nextSeq = contours; nextSeq != null; nextSeq = nextSeq.h_next()) {
contr = cvBoundingRect(nextSeq, 0);
if ((contr.width() >= maxWidth) && (contr.height() >= maxHeight)) {
maxHeight = contr.height();
maxWidth = contr.width();
seqFound = nextSeq;
}
}
opencv_core.CvSeq result = cvApproxPoly(seqFound, Loader.sizeof(opencv_core.CvContour.class), memory, CV_POLY_APPROX_DP, cvContourPerimeter(seqFound) * 0.1, 0);
return result;
}
Sorry this should be in comments but I don't have enough reputation. What I can see from your code is that the canny is applied on a downscaled image and so is the contour. You are drawing the lines on the original image (which isn't downscaled by percent) so naturally it wouldn't look correct (if it isn't looking correct but something is being drawn). Otherwise, you should mention the color space of the image, it doesn't matter for drawing but does for canny.

Transformation of a bitmap- Android

I'm having a bit of a problem with a (very basic and crude) implementation of Parallax. Basically I have an image which is supposed to move across the screen at a slightly different rate to the background. It does this- until it reaches the end of the image. It seems to loop back to the start of the image-- but when it reaches the end of the image, it seems to stretch the bitmap out across the length of the screen until it's stretched out completely- then it resets itself.
I can't attach a screenshot (not enough rep) but here's the code.
Init method:
private void init(Context context) {
screenSize = new Point();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getSize(screenSize);
backGroundViewPort = new Rect();
cityscapeRect = new Rect();
backGroundViewPort.set(0, 0, 400, 300);
GGRAssetManager ggrAssetManager = new GGRAssetManager(context);
background = ggrAssetManager.loadImage("background.jpg");
cityscape = ggrAssetManager.loadImage("cityscape3.png");
clouds = ggrAssetManager.loadImage("clouds.png");
backGroundViewPort.set(0, 0, 400, 300);
}
DoUpdate method:
public void doUpdate() {
Game.getInstance().viewport.set(Math.max(0, (int) (game.getPlayer().getxPos() - screenSize.x / 2)),
0,
(int) (game.getPlayer().getxPos() + (screenSize.x / 2)),
screenSize.y);
if (backGroundViewPort.right + 1 >= background.getWidth()) {
backGroundViewPort.left = 0;
backGroundViewPort.right = 400;
} else {
backGroundViewPort.right += 1;
backGroundViewPort.left += 1;
}
if (cityscapeRect.right + 1 >= cityscape.getWidth()) {
cityscapeRect.left = cityscape.getWidth() - screenSize.x;
cityscapeRect.right = 0;
} else {
cityscapeRect.right += 1;
cityscapeRect.left += 1;
}
}
DoDraw method:
public void doDraw(Canvas canvas) {
//PARALLAX
backGroundRect.set(0, 0, screenSize.x, screenSize.y);
canvas.drawBitmap(background, backGroundViewPort, backGroundRect, null);
cityscapeRect.set(0, screenSize.y/2, (screenSize.x), screenSize.y);
Paint paint = new Paint();
paint.setAlpha(150);
canvas.drawBitmap(cityscape, backGroundViewPort, cityscapeRect, paint);
}
I'm sure it's to do with the rectangles, but I don't know how to fix it. Help is greatly appreciated.

Can't get colored image on Android usin objloader library

I have made a sketch in processing using saitoobjloader and controlP5 librarys, and it works just fine, and after that i have exported as an android app to import it in eclipse. I have runned it then on my phone, from eclipse, and it works, except that, everything is black and white.I have tried model.disableMaterial(), model.disableTexture() and it does not work, I have seted for android 2.3.3, 4.2.2, 4.4 and it also don't work...stil black and white. I have tried primitive debug by disabeling everything i can one by one: the animation, the boject loaded, screen orientation and stil black and white. Idon't have any permisions aded, and the only change i have made is for screen orientation in manifes aplication: Debuggable --> null, Screen orientation --> unspecified, Config changes --> orientation.
Below you can see my code from eclipse:
package processing.test.my_cnc_obj_with_gui_mooving_animation;
import processing.core.*;
import android.content.res.Configuration;
import saito.objloader.*;
import controlP5.*;
public class My_cnc_obj_with_GUI_mooving_animation extends PApplet {
OBJModel model;
ControlP5 sb;
float rotX;
float rotY;
float zoom = 1;
float translateX;
float translateY;
float k;
int i;
float initlength = 250;
int initlengthX = 150;
int initlengthY = 150;
int initlengthZ = 80;
float moveIndex;
float AXA_X;
float AXA_Y;
float AXA_Z;
public void setup() {
model = new OBJModel(this, "CNC colorat pentru processing.obj");
model.scale(400);
model.translateToCenter();
//model.disableTexture();
model.disableMaterial();
//model.disableDebug();
controlereGUI();
noStroke();
}
public void draw() {
background(50, 34, 32);
lights();
// fill(255,0,255);
pushMatrix();
translate(width/2 - 50, height/2, 0);
rotateX(rotY);
rotateY(rotX);
model.draw();
model.disableMaterial();
popMatrix();
animation();
}
public void mouseDragged()
{
rotX += (mouseX - pmouseX) * 0.01f;
rotY -= (mouseY - pmouseY) * 0.01f;
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
model.disableMaterial();
//Something strange happened... bail out!
if(orientation == Configuration.ORIENTATION_UNDEFINED)
return;
orientation = Configuration.ORIENTATION_PORTRAIT;
if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Landscape config
}
if(orientation == Configuration.ORIENTATION_PORTRAIT) {
//Portrait config
}
}
/*public void mouseWheel(MouseEvent e) {
translateX = translateX-e.getAmount()*(mouseX)/100;
translateY = translateY-e.getAmount()*(mouseY)/100;
zoom += e.getAmount() / 100;
model.scale(zoom);
}*/
public void controlereGUI() {
sb = new ControlP5(this);
sb.getTab("default")
//.activateTab("Assisted_controll")
//.activateEvent(true)
.setHeight(40)
.setLabel("Assisted controll")
.setId(3)
;
sb.getTab("Manual_controll")
//.activateTab("Manual_controll")
//.activateEvent(true)
.setHeight(40)
.setLabel("Manual controll")
.setId(1)
;
sb.addTab("Settings")
//.activateTab("Settings")
.setHeight(40)
.setWidth(60)
.setLabel("Settings")
.setId(2)
.setColorBackground(color(0, 160, 100))
//.activateEvent(true)
.setColorLabel(color(255))
.setColorActive(color(255, 128, 0))
;
sb.addSlider("AXA_X")
.setPosition(10, 70)
//.setWidth(300)
.setSize(300, 30)
.setRange(initlength, 0)
//.setValue(128)
.setSliderMode(Slider.FLEXIBLE)
;
sb.addSlider("AXA_Y")
.setPosition(10, 110)
//.setWidth(300)
.setSize(300, 30)
.setRange(initlengthY, -initlengthY)
//.setValue(128)
.setSliderMode(Slider.FLEXIBLE)
.setColorForeground(0xffFC0000)
.setColorBackground(color(150, 0, 0))
;
sb.addSlider("AXA_Z")
.setPosition(10, 150)
//.setWidth(300)
.setSize(300, 30)
.setRange(initlengthZ + 120, 70)
//.setValue(128)
.setSliderMode(Slider.FLEXIBLE)
.setColorForeground(0xff0BFC00)
.setColorBackground(color(100, 150, 0))
;
sb.addButton("Start_movement")
.setBroadcast(false)
.setValue(128)
.setPosition(120, height-160)
//.setImages(imgs)
.setSize(90, 50)
.setCaptionLabel("Start movement")
.setColorBackground(color(100, 150, 0))
//.setVisible(false)
.setBroadcast(true)
;
sb.addButton("Stop_movement")
.setValue(128)
.setPosition(120, height-100)
//.setImages(imgs)
.setSize(90, 50)
.setCaptionLabel("Stop movement")
.setColorBackground(color(150, 0, 0))
//.setVisible(false)
;
}
public void animation() {
for (int i = 0; i < model.getVertexCount () - 6090; i++) {
PVector orgv = model.getVertex(i);
PVector tmpv = new PVector();
tmpv.x = orgv.x;
tmpv.y = orgv.y;
tmpv.z = orgv.z + (k * AXA_Y);
model.setVertex(i, tmpv);
}
if ((AXA_Y != 0)) {
if (moveIndex < AXA_Y)
moveIndex ++;
else
if (moveIndex > AXA_Y)
moveIndex --;
else
k = 0;
k = 1;
} else {
moveIndex = AXA_Y;
k = 0;
}
}
public int sketchWidth() { return 800; }
public int sketchHeight() { return 700; }
public String sketchRenderer() { return P3D; }
}
I don'tknow why is stil black and white.
Thanks in advance.
Solved.
It seems that i must use a combination of use of material (not disable it) and after drawing the model to stop the lights. So, it should be like in the code above, with this modifications:
public void setup() {
model = new OBJModel(this, "CNC colorat pentru processing.obj");
model.scale(400);
model.translateToCenter();
controlereGUI();
noStroke();
}
public void draw() {
background(50, 34, 32);
lights();
// fill(255,0,255);
pushMatrix();
translate(width/2 - 50, height/2, 0);
rotateX(rotY);
rotateY(rotX);
model.draw();
popMatrix();
noLights();
animation();
}
However, it seems that the 3D model remains still black and white even if is coloured. The 3D model was modified with Blender v2.71 (imported as .wrl file and exported as .obj with .mtl file). The .wrl file has been initial colored and when it was imported in Blender everything was ok, the model was colored. It seems that processing can't get the material. The debug shows: Material 'Shape.1687' not defined, ..., Material 'Shape.001' not defined,
Material 'Shape' not defined
I don't know where the problem is: inside saitoobjloader or the .obj and .mtl files....
Solved the second problem too. The problem is in file's name "CNC colorat pentru processing".
It seems that saito's objloader parser does not read spaces caracter (" ") in files name, so when i am making a new obj file (in blender or any other), i should have save it with the name "CNC_colorat_pentru_processing", or any other name that does not contain space caracter.

libgdx particleEffect rotation

I draw fire on my android device with libgdx:
ParticleEffect effect;
ParticleEffectPool fireEffectPool;
Array<PooledEffect> effects = new Array<PooledEffect>();
#Override
public void create()
{
...
effect = new ParticleEffect();
effect.load(Gdx.files.internal("particles/fire01.p"), Gdx.files.internal("image"));
effect.setFlip(true, false);
fireEffectPool = new ParticleEffectPool(effect, 1000, 3000);
PooledEffect myEffect = fireEffectPool.obtain();
myEffect.setPosition(200, 400);
effects.add(myEffect);
...
}
Can I rotate, set speed or scale my effect programmatically?
I found the solution to the particle effect rotation problem by using this code as base
http://badlogicgames.com/forum/viewtopic.php?f=11&t=7060#p32607
And adding a small change to conserve the amplitude of the effect. Hope it helps.
public void rotateBy(float amountInDegrees) {
Array<ParticleEmitter> emitters = particleEffect.getEmitters();
for (int i = 0; i < emitters.size; i++) {
ScaledNumericValue val = emitters.get(i).getAngle();
float amplitude = (val.getHighMax() - val.getHighMin()) / 2f;
float h1 = amountInDegrees + amplitude;
float h2 = amountInDegrees - amplitude;
val.setHigh(h1, h2);
val.setLow(amountInDegrees);
}
}
}
Yes. Check out the ParticleEmitterTest: https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/ParticleEmitterTest.java
You just need to obtain a ParticleEmitter:
emitter = effect.getEmitters().first();
emitter.getScale().setHigh(5, 20);

Categories

Resources