Paint event doesn't invoked - c#

Trying to implement a random walk by moving the ball across the screen. Algorithm is looks like working but debug shows that the paint event doesn't invoked.
First of all, try to do this in pattern MVC. For clarity, I will give the code of these components.
View:
public partial class ViewBallBounce : Form, Observer
{
private ModelRandomWalk modelRandomWalk;
private ControllerRandomWalk controllerRandomWalk;
static int i = 0;
public ViewBallBounce(ModelRandomWalk _modelRandomWalk)
{
InitializeComponent();
this.modelRandomWalk = _modelRandomWalk;
controllerRandomWalk = new ControllerRandomWalk(modelRandomWalk, this, ClientSize.Width, ClientSize.Height);
modelRandomWalk.Register(this);
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
this.UpdateStyles();
}
public void UpdateState()
{
this.Refresh();
}
private void ViewBallBounce_Load(object sender, EventArgs e)
{
controllerRandomWalk.Bounce();
}
private void ViewBallBounce_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.Clear(BackColor);
i++;
g.FillEllipse(Brushes.Blue, modelRandomWalk.X, modelRandomWalk.Y,
modelRandomWalk.Width, modelRandomWalk.Height);
g.DrawEllipse(Pens.Black, modelRandomWalk.X, modelRandomWalk.Y,
modelRandomWalk.Width, modelRandomWalk.Height);
}
}
Control:
public class ControllerRandomWalk
{
private ModelRandomWalk modelRandomWalk;
private ViewBallBounce viewBallBounce;
public int clientH, clientW;
public ControllerRandomWalk(ModelRandomWalk modelRandomWalk, ViewBallBounce viewBallBounce, int _width, int _height)
{
this.modelRandomWalk = modelRandomWalk;
this.viewBallBounce = viewBallBounce;
this.clientH = _height;
this.clientW = _width;
}
public int Bounce()
{
return modelRandomWalk.bounce(100, clientH, clientW);
}
}
Model:
public class ModelRandomWalk
{
private int x, y;
private int velocityX, velocityY;
private int width, height;
public int X { get { return x; } }
public int Y { get { return y; } }
public int VelocityX { get { return velocityX; } }
public int VelocityY { get { return velocityY; } }
public int Width { get { return width; } }
public int Height { get { return height; } }
public void updatePosition(int key)
{
if (key == 0) this.x += velocityX;
else this.y += velocityY;
}
public void updateVelocity(int key)
{
if (key == 0) this.velocityX = -this.velocityX;
else this.velocityY = -this.velocityY;
}
public ModelRandomWalk(int _x, int _y, int _width, int _height)
{
this.x = _x;
this.y = _y;
this.width = _width;
this.height = _height;
}
public int bounce(int _steps, int _h, int _w)
{
int steps = _steps;
int clientH = _h, clientW = _w;
for(int i = 0; i < steps; i++)
{
Random rnd = new Random();
int v = rnd.Next(0, 4); // 0 = +v_x, 1 = +v_y, 2 = -v_x, 3 = -v_y
switch (v)
{
case 0:
velocityX++;
break;
case 1:
velocityY++;
break;
case 2:
velocityX--;
break;
case 3:
velocityY--;
break;
}
updatePosition(0);
if (X < 0)
{
x = 6;
updateVelocity(0);
}
else if (X + Width > clientW)
{
x = clientW - 6;
updateVelocity(0);
}
updatePosition(1);
if (Y < 0)
{
y = 6;
updateVelocity(1);
}
else if (Y + Height > clientH)
{
y = clientH - 6;
updateVelocity(1);
}
UpdateObservers();
}
return 0;
}
private ArrayList listeners = new ArrayList();
public void Register(Observer o)
{
listeners.Add(o);
o.UpdateState();
}
public void Deregister(Observer o)
{
listeners.Remove(0);
}
public void UpdateObservers()
{
foreach (Observer el in listeners)
{
el.UpdateState();
}
}
}
Sorry for long post. The main problem in these lines, when ViewBallBounce_Paint doesn't invoke.
public void UpdateState()
{
this.Refresh();
}
private void ViewBallBounce_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.Clear(BackColor);
i++; //just checking has it invoked
g.FillEllipse(Brushes.Blue, modelRandomWalk.X, modelRandomWalk.Y,
modelRandomWalk.Width, modelRandomWalk.Height);
g.DrawEllipse(Pens.Black, modelRandomWalk.X, modelRandomWalk.Y,
modelRandomWalk.Width, modelRandomWalk.Height);
}
I have tried a lot of ways to set breakpoints and don't understand why after Refresh nothing happens. By the way, breakpoint in ViewBallBounce_Paint shows very strange modelRandomWalk.X or modelRandomWalk.Y as 224 or -78 and they don't change.
What's could be wrong?
UPD: New form is openned and the ball is drawen but it doesn't move. Changed steps in cycle to 10 and find out ball had moved only after ending the cycle in Model Component. Nevertheless, this.Refresh has worked but the paint event has invoked after 10 iterations. By the way, the movement occurred taking into account the changes in speeds and positions in the Model component. Wrote Thread.Sleep(1000) in ViewBallBounce_Paint but there were no changes.

Related

Xamarin Binding Libriary 'Overlay': member names cannot be the same as their enclosing type

I'm need rename field "Overlay", but not remove.
I'm try make link native jar lib to xamarin dll.
I`m create new Binding Libriary project and include jar file inside.
But when i'm try build solution, system output window get error
'Overlay': member names cannot be the same as their enclosing type.
I'm try configurate MetaData file in the following way.
<metadata>
<remove-node path="/api/package[#name='Com.Cdcom.Naviapps.Progorod']/class[#name='Overlay']/method[#name='Overlay']" />
</metadata>
or
<remove-node path="/api/package[#name='Com.Cdcom.Naviapps.Progorod']/class[#name='Overlay']" />
or i'm try change EnumMethods
<enum-method-mappings>
<mapping jni-class="/api/package[#name='com.cdcom.naviapps.progorod']/class[#name='Overlay']">
<method jni-name="Overlay" parameter="return" clr-enum-type="Android.OS.Overlay" />
</mapping>
</enum-method-mappings>
but i'm get other error
"generator.exe" exited with code -532462766.
You can see the class from first error below
// Metadata.xml XPath class reference: path="/api/package[#name='com.cdcom.naviapps.progorod']/class[#name='Overlay']"
[global::Android.Runtime.Register ("com/cdcom/naviapps/progorod/Overlay", DoNotGenerateAcw=true)]
public partial class Overlay : global::Java.Lang.Object {
//region "Event implementation for Com.Cdcom.Naviapps.Progorod.Overlay.IOnOverlayListener"
public event EventHandler<global::Com.Cdcom.Naviapps.Progorod.Overlay.OverlayEventArgs> Overlay {
add {
global::Java.Interop.EventHelper.AddEventHandler<global::Com.Cdcom.Naviapps.Progorod.Overlay.IOnOverlayListener, global::Com.Cdcom.Naviapps.Progorod.Overlay.IOnOverlayListenerImplementor>(
ref weak_implementor___SetOnOverlayListener,
__CreateIOnOverlayListenerImplementor,
__v => OnOverlayListener = __v,
__h => __h.Handler += value);
}
remove {
global::Java.Interop.EventHelper.RemoveEventHandler<global::Com.Cdcom.Naviapps.Progorod.Overlay.IOnOverlayListener, global::Com.Cdcom.Naviapps.Progorod.Overlay.IOnOverlayListenerImplementor>(
ref weak_implementor___SetOnOverlayListener,
global::Com.Cdcom.Naviapps.Progorod.Overlay.IOnOverlayListenerImplementor.__IsEmpty,
__v => OnOverlayListener = null,
__h => __h.Handler -= value);
}
}
//endregion
}
Original java code
public class Overlay
{
public List<OverlayItem> getItems()
{
return this.mOverlayItems;
}
public OnOverlayListener getOnOverlayListener()
{
return this.mOverlayListener;
}
public void populate()
{
double[] latlon = new double[this.mOverlayItems.size() * 2];
int d = 0;
for (OverlayItem oi : this.mOverlayItems)
{
latlon[(d++)] = oi.getGeoPoint().getLatitude();
latlon[(d++)] = oi.getGeoPoint().getLongitude();
}
Native.populateOverlay(this.mId, latlon);
}
public void setBitmap(Bitmap bitmap, float xOffset, float yOffset, boolean isPlain, int sizeInMeters)
{
int width = 0;
int height = 0;
int[] pixels = null;
if (bitmap != null)
{
width = bitmap.getWidth();
height = bitmap.getHeight();
pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
}
Native.setOverlayBitmap(this.mId, width, height, pixels, xOffset, yOffset, isPlain, sizeInMeters);
}
public void setOnOverlayListener(OnOverlayListener listener)
{
this.mOverlayListener = listener;
}
public static int SPECIAL_OVERLAY_START_ROUTE = -1;
public static int SPECIAL_OVERLAY_FINISH_ROUTE = -2;
public static int SPECIAL_OVERLAY_ROUTE_SPRITE = -3;
public static int SPECIAL_OVERLAY_GEOBLOG_SPRITE = -4;
private static int SPECIAL_OVERLAYS_COUNT = 4;
public static Overlay specialOverlay(int id)
{
if (mSpecialOverlays[(id + SPECIAL_OVERLAYS_COUNT)] == null)
{
mSpecialOverlays[(id + SPECIAL_OVERLAYS_COUNT)] = new Overlay();
mSpecialOverlays[(id + SPECIAL_OVERLAYS_COUNT)].mId = id;
}
return mSpecialOverlays[(id + SPECIAL_OVERLAYS_COUNT)];
}
protected int getId()
{
return this.mId;
}
protected int mId = mNextId++;
private static int mNextId = 1;
private List<OverlayItem> mOverlayItems = new ArrayList();
private OnOverlayListener mOverlayListener;
private static Overlay[] mSpecialOverlays = new Overlay[SPECIAL_OVERLAYS_COUNT];
public static abstract interface OnOverlayListener
{
public abstract void onOverlayEvent(Overlay paramOverlay, OverlayItem paramOverlayItem);
}
}

Form is opening in Background once the Splash Screen is getting closed

I have created a splash screen. On my splash screen I have given a progress bar and two buttons to perform some action. On button click I am displaying respective forms once the modules of those forms are getting loaded completely along with showing the progress on progress bar. Once the respective form will open, Splash screen shall be closed and Form should be shown on top of the screen.
But the issue is that after the splash screen closing, My form is opening in background or you can say getting out of focus which should not happen. I have checked various solutions given on google or stackoverflow but could not able to resolve my problem.
Following is my code :
SplashScreen.cs
// <--- Data Members
// --->
public SplashScreen()
{
InitializeComponent();
this.Opacity = 0.0;
UpdateTimer.Interval = TIMER_INTERVAL;
UpdateTimer.Start();
this.ClientSize = this.BackgroundImage.Size;
}
static public void ShowSplashScreen()
{
if (ms_frmSplash != null)
{
return;
}
ms_oThread = new Thread(new ThreadStart(SplashScreen.ShowForm));
ms_oThread.IsBackground = true;
ms_oThread.SetApartmentState(ApartmentState.STA);
ms_oThread.Start();
while (ms_frmSplash == null || ms_frmSplash.IsHandleCreated == false)
{
System.Threading.Thread.Sleep(TIMER_INTERVAL);
}
}
static public void CloseForm()
{
if (ms_frmSplash != null && ms_frmSplash.IsDisposed == false)
{
ms_frmSplash.m_dblOpacityIncrement = -ms_frmSplash.m_dblOpacityDecrement;
}
ms_oThread = null;
ms_frmSplash = null;
}
static public void SetStatus(string newStatus)
{
SetStatus(newStatus, true);
}
static public void SetStatus(string newStatus, bool setReference)
{
if (ms_frmSplash == null)
{
return;
}
ms_frmSplash.m_sStatus = newStatus;
if (setReference)
{
ms_frmSplash.SetReferenceInternal();
}
}
static public void SetReferencePoint()
{
if (ms_frmSplash == null)
{
return;
}
ms_frmSplash.SetReferenceInternal();
}
static private void ShowForm()
{
ms_frmSplash = new SplashScreen();
Application.Run(ms_frmSplash);
}
private void SetReferenceInternal()
{
if (m_bDTSet == false)
{
m_bDTSet = true;
m_dtStart = DateTime.Now;
ReadIncrements();
}
double dblMilliseconds = ElapsedMilliSeconds();
m_alActualTimes.Add(dblMilliseconds);
m_dblLastCompletionFraction = m_dblCompletionFraction;
if (m_alPreviousCompletionFraction != null && m_iIndex < m_alPreviousCompletionFraction.Count)
{
m_dblCompletionFraction = (double)m_alPreviousCompletionFraction[m_iIndex++];
}
else
{
m_dblCompletionFraction = (m_iIndex > 0) ? 1 : 0;
}
}
private double ElapsedMilliSeconds()
{
TimeSpan ts = DateTime.Now - m_dtStart;
return ts.TotalMilliseconds;
}
private void ReadIncrements()
{
string sPBIncrementPerTimerInterval = SplashScreenXMLStorage.Interval;
double dblResult;
if (Double.TryParse(sPBIncrementPerTimerInterval, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out dblResult) == true)
{
m_dblPBIncrementPerTimerInterval = dblResult;
}
else
{
m_dblPBIncrementPerTimerInterval = .0015;
}
string sPBPreviousPctComplete = SplashScreenXMLStorage.Percents;
if (sPBPreviousPctComplete != "")
{
string[] aTimes = sPBPreviousPctComplete.Split(null);
m_alPreviousCompletionFraction = new ArrayList();
for (int i = 0; i < aTimes.Length; i++)
{
double dblVal;
if (Double.TryParse(aTimes[i], System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out dblVal) == true)
{
m_alPreviousCompletionFraction.Add(dblVal);
}
else
{
m_alPreviousCompletionFraction.Add(1.0);
}
}
}
else
{
m_bFirstLaunch = true;
m_sTimeRemaining = "";
}
}
private void StoreIncrements()
{
string sPercent = "";
double dblElapsedMilliseconds = ElapsedMilliSeconds();
for (int i = 0; i < m_alActualTimes.Count; i++)
{
sPercent += ((double)m_alActualTimes[i] / dblElapsedMilliseconds).ToString("0.####", System.Globalization.NumberFormatInfo.InvariantInfo) + " ";
}
SplashScreenXMLStorage.Percents = sPercent;
m_dblPBIncrementPerTimerInterval = 1.0 / (double)m_iActualTicks;
SplashScreenXMLStorage.Interval = m_dblPBIncrementPerTimerInterval.ToString("#.000000", System.Globalization.NumberFormatInfo.InvariantInfo);
}
public static SplashScreen GetSplashScreen()
{
return ms_frmSplash;
}
private void UpdateTimer_Tick(object sender, System.EventArgs e)
{
if (Program.isRadarSelected)
{
if (count >= 100)
{
UpdateTimer.Stop();
this.Close();
}
else
{
updateProgressBar();
count += 5;
}
}
if (m_dblOpacityIncrement > 0)
{
m_iActualTicks++;
if (this.Opacity < 1)
{
this.Opacity += m_dblOpacityIncrement;
}
}
else
{
if (this.Opacity > 0)
{
this.Opacity += m_dblOpacityIncrement;
}
else
{
StoreIncrements();
UpdateTimer.Stop();
this.Close();
}
}
}
private void updateProgressBar()
{
SplashScreen.SetStatus("Loading : " + count + " %");
statusLabel.Text = m_sStatus;
m_dblLastCompletionFraction += m_dblPBIncrementPerTimerInterval;
int width = (int)Math.Floor(statusPanel.ClientRectangle.Width * m_dblLastCompletionFraction);
int height = statusPanel.ClientRectangle.Height;
int x = statusPanel.ClientRectangle.X;
int y = statusPanel.ClientRectangle.Y;
if (width > 0 && height > 0)
{
m_rProgress = new Rectangle(x, y, width, height);
if (!statusPanel.IsDisposed)
{
Graphics g = statusPanel.CreateGraphics();
LinearGradientBrush brBackground = new LinearGradientBrush(m_rProgress, Color.FromArgb(58, 96, 151), Color.FromArgb(181, 237, 254), LinearGradientMode.Horizontal);
g.FillRectangle(brBackground, m_rProgress);
g.Dispose();
}
}
}
private void RadarSelectionButton_Click(object sender, EventArgs e)
{
Program.isButtonClicked= true;
}
Program.cs
internal static class Program
{
public static bool isButtonClicked= false;
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SplashScreen.ShowSplashScreen();
Application.DoEvents();
while (!isButtonClicked)
{
System.Threading.Thread.Sleep(50);
}
Application.Run(new MyForm());
SplashScreen.CloseForm();
}
}
As far as I remember Application.Run(...) is blocking, meaning that your splash screen would never close before the main window is closed. You could try the code below. Let me know how it goes.
internal static class Program
{
public static bool isButtonClicked= false;
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SplashScreen.ShowSplashScreen();
Application.DoEvents();
while (!isButtonClicked)
{
System.Threading.Thread.Sleep(50);
}
var window = new MyForm();
window.Load += (s, e) =>
{
SplashScreen.CloseForm();
window.Activate();
}
Application.Run(window);
}
}
Regarding you CloseForm method, I am unsure how you intended it to work. The only thing you are doing is setting the opacity? But as far as you write this is not your issue. But I would think that you need to signal the main window of the splash screen to close, before the Application.Run(..) would exit.
And also the while loop in the ShowSplashScreen method; Why? Consider using stuff like ManualResetEvent for waiting and signaling between threads. Always better to wait for an event rather than polling.

Set maximum value for the progress bar to match length of queue.

I would like to visualize how a queue when accessed by two reader threads and a writer thread grows and shrinks, with help of a progressbar in mainform. I will use a delegate to invoke the progress bar in main form and set its value to Queue.Value ( Toys.lenght). The progressbar does not behave as stated, it does not grow all the way and the lenght variables does not either.
public class Buffer
{
private delegate void Display(int v, ProgressBar f );
private Queue<Toy> Toys = new Queue<Toy>();
private object MyLock = new object();
private int max;
private int lenght;
private ProgressBar progressbar1;
public Buffer(ProgressBar r)
{
this.progressbar1 = r;
this.max = 10;
this.lenght = Toys.Count;
}
public void writeMethod(Toy toy)
{
lock (MyLock)
{
if (Toys.Count == max)
{
Monitor.Wait(MyLock);
}
Toys.Enqueue(toy);
Monitor.PulseAll(MyLock);
progressbar1.Invoke(new Display(Disp), new object[] {Toys.Count, progressbar1});
MessageBox.Show("Que contains these items" + lenght);
}
}
public void readMethod()
{
lock (MyLock)
{
if(Toys.Count == 0)
{
Monitor.Wait(MyLock);
}
Toys.Dequeue();
Monitor.PulseAll(MyLock);
}
}
public void Disp(int I, ProgressBar l)
{
progressbar1.Value = I;
}
}
}
Double check the variable lenght, use count instead. Change Progressbar default setting for maximum size from 100 to 10 to match size of the queue Toys. In Disp method change from = I to += I;
{
public class Buffer
{
private delegate void Display(int v, ProgressBar f );
private Queue<Toy> Toys = new Queue<Toy>();
private object MyLock = new object();
private int max;
private int lenght;
private ProgressBar progressbar1;
public Buffer(ProgressBar r)
{
this.progressbar1 = r;
this.max = 10;
this.lenght = Toys.Count;
}
public void writeMethod(Toy toy)
{
lock (MyLock)
{
if (Toys.Count >= max)
{
Monitor.Wait(MyLock);
}
if(Toys.Count <= max)
{
Toys.Enqueue(toy);
progressbar1.Invoke(new Display(Disp), new object[] {Toys.Count, progressbar1});
}
Monitor.PulseAll(MyLock);
MessageBox.Show("Que contains these items" + Toys.Count);
}
}
public void readMethod()
{
lock (MyLock)
{
if(Toys.Count == 0)
{
Monitor.Wait(MyLock);
}
Toys.Dequeue();
Monitor.PulseAll(MyLock);
}
}
public void Disp(int I, ProgressBar l)
{
progressbar1.Value += I;
}
}
}

Binding Library Mono for Android

I want to build an application with monodroid to have a live video stream from an IPCamera (with MJpeg format) to my tablet. after digging the internet I found that there is a Mjpeg Library project written in Java from here. it has two files MjpegView.java and MjpegInputStream.Java which I put them both here:
MjpegView.java
package de.mjpegsample.MjpegView;
import java.io.IOException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MjpegView extends SurfaceView implements SurfaceHolder.Callback {
public final static int POSITION_UPPER_LEFT = 9;
public final static int POSITION_UPPER_RIGHT = 3;
public final static int POSITION_LOWER_LEFT = 12;
public final static int POSITION_LOWER_RIGHT = 6;
public final static int SIZE_STANDARD = 1;
public final static int SIZE_BEST_FIT = 4;
public final static int SIZE_FULLSCREEN = 8;
private MjpegViewThread thread;
private MjpegInputStream mIn = null;
private boolean showFps = false;
private boolean mRun = false;
private boolean surfaceDone = false;
private Paint overlayPaint;
private int overlayTextColor;
private int overlayBackgroundColor;
private int ovlPos;
private int dispWidth;
private int dispHeight;
private int displayMode;
public class MjpegViewThread extends Thread {
private SurfaceHolder mSurfaceHolder;
private int frameCounter = 0;
private long start;
private Bitmap ovl;
public MjpegViewThread(SurfaceHolder surfaceHolder, Context context) { mSurfaceHolder = surfaceHolder; }
private Rect destRect(int bmw, int bmh) {
int tempx;
int tempy;
if (displayMode == MjpegView.SIZE_STANDARD) {
tempx = (dispWidth / 2) - (bmw / 2);
tempy = (dispHeight / 2) - (bmh / 2);
return new Rect(tempx, tempy, bmw + tempx, bmh + tempy);
}
if (displayMode == MjpegView.SIZE_BEST_FIT) {
float bmasp = (float) bmw / (float) bmh;
bmw = dispWidth;
bmh = (int) (dispWidth / bmasp);
if (bmh > dispHeight) {
bmh = dispHeight;
bmw = (int) (dispHeight * bmasp);
}
tempx = (dispWidth / 2) - (bmw / 2);
tempy = (dispHeight / 2) - (bmh / 2);
return new Rect(tempx, tempy, bmw + tempx, bmh + tempy);
}
if (displayMode == MjpegView.SIZE_FULLSCREEN) return new Rect(0, 0, dispWidth, dispHeight);
return null;
}
public void setSurfaceSize(int width, int height) {
synchronized(mSurfaceHolder) {
dispWidth = width;
dispHeight = height;
}
}
private Bitmap makeFpsOverlay(Paint p, String text) {
Rect b = new Rect();
p.getTextBounds(text, 0, text.length(), b);
int bwidth = b.width()+2;
int bheight = b.height()+2;
Bitmap bm = Bitmap.createBitmap(bwidth, bheight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bm);
p.setColor(overlayBackgroundColor);
c.drawRect(0, 0, bwidth, bheight, p);
p.setColor(overlayTextColor);
c.drawText(text, -b.left+1, (bheight/2)-((p.ascent()+p.descent())/2)+1, p);
return bm;
}
public void run() {
start = System.currentTimeMillis();
PorterDuffXfermode mode = new PorterDuffXfermode(PorterDuff.Mode.DST_OVER);
Bitmap bm;
int width;
int height;
Rect destRect;
Canvas c = null;
Paint p = new Paint();
String fps = "";
while (mRun) {
if(surfaceDone) {
try {
c = mSurfaceHolder.lockCanvas();
synchronized (mSurfaceHolder) {
try {
bm = mIn.readMjpegFrame();
destRect = destRect(bm.getWidth(),bm.getHeight());
c.drawColor(Color.BLACK);
c.drawBitmap(bm, null, destRect, p);
if(showFps) {
p.setXfermode(mode);
if(ovl != null) {
height = ((ovlPos & 1) == 1) ? destRect.top : destRect.bottom-ovl.getHeight();
width = ((ovlPos & 8) == 8) ? destRect.left : destRect.right -ovl.getWidth();
c.drawBitmap(ovl, width, height, null);
}
p.setXfermode(null);
frameCounter++;
if((System.currentTimeMillis() - start) >= 1000) {
fps = String.valueOf(frameCounter)+"fps";
frameCounter = 0;
start = System.currentTimeMillis();
ovl = makeFpsOverlay(overlayPaint, fps);
}
}
} catch (IOException e) {}
}
} finally { if (c != null) mSurfaceHolder.unlockCanvasAndPost(c); }
}
}
}
}
private void init(Context context) {
SurfaceHolder holder = getHolder();
holder.addCallback(this);
thread = new MjpegViewThread(holder, context);
setFocusable(true);
overlayPaint = new Paint();
overlayPaint.setTextAlign(Paint.Align.LEFT);
overlayPaint.setTextSize(12);
overlayPaint.setTypeface(Typeface.DEFAULT);
overlayTextColor = Color.WHITE;
overlayBackgroundColor = Color.BLACK;
ovlPos = MjpegView.POSITION_LOWER_RIGHT;
displayMode = MjpegView.SIZE_STANDARD;
dispWidth = getWidth();
dispHeight = getHeight();
}
public void startPlayback() {
if(mIn != null) {
mRun = true;
thread.start();
}
}
public void stopPlayback() {
mRun = false;
boolean retry = true;
while(retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public MjpegView(Context context, AttributeSet attrs) { super(context, attrs); init(context); }
public void surfaceChanged(SurfaceHolder holder, int f, int w, int h) { thread.setSurfaceSize(w, h); }
public void surfaceDestroyed(SurfaceHolder holder) {
surfaceDone = false;
stopPlayback();
}
public MjpegView(Context context) { super(context); init(context); }
public void surfaceCreated(SurfaceHolder holder) { surfaceDone = true; }
public void showFps(boolean b) { showFps = b; }
public void setSource(MjpegInputStream source) { mIn = source; startPlayback();}
public void setOverlayPaint(Paint p) { overlayPaint = p; }
public void setOverlayTextColor(int c) { overlayTextColor = c; }
public void setOverlayBackgroundColor(int c) { overlayBackgroundColor = c; }
public void setOverlayPosition(int p) { ovlPos = p; }
public void setDisplayMode(int s) { displayMode = s; }
}
MjpegInputStream.Java
package de.mjpegsample.MjpegView;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Properties;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class MjpegInputStream extends DataInputStream {
private final byte[] SOI_MARKER = { (byte) 0xFF, (byte) 0xD8 };
private final byte[] EOF_MARKER = { (byte) 0xFF, (byte) 0xD9 };
private final String CONTENT_LENGTH = "Content-Length";
private final static int HEADER_MAX_LENGTH = 100;
private final static int FRAME_MAX_LENGTH = 40000 + HEADER_MAX_LENGTH;
private int mContentLength = -1;
public static MjpegInputStream read(String url) {
HttpResponse res;
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
res = httpclient.execute(new HttpGet(URI.create(url)));
return new MjpegInputStream(res.getEntity().getContent());
} catch (ClientProtocolException e) {
} catch (IOException e) {}
return null;
}
public MjpegInputStream(InputStream in) { super(new BufferedInputStream(in, FRAME_MAX_LENGTH)); }
private int getEndOfSeqeunce(DataInputStream in, byte[] sequence) throws IOException {
int seqIndex = 0;
byte c;
for(int i=0; i < FRAME_MAX_LENGTH; i++) {
c = (byte) in.readUnsignedByte();
if(c == sequence[seqIndex]) {
seqIndex++;
if(seqIndex == sequence.length) return i + 1;
} else seqIndex = 0;
}
return -1;
}
private int getStartOfSequence(DataInputStream in, byte[] sequence) throws IOException {
int end = getEndOfSeqeunce(in, sequence);
return (end < 0) ? (-1) : (end - sequence.length);
}
private int parseContentLength(byte[] headerBytes) throws IOException, NumberFormatException {
ByteArrayInputStream headerIn = new ByteArrayInputStream(headerBytes);
Properties props = new Properties();
props.load(headerIn);
return Integer.parseInt(props.getProperty(CONTENT_LENGTH));
}
public Bitmap readMjpegFrame() throws IOException {
mark(FRAME_MAX_LENGTH);
int headerLen = getStartOfSequence(this, SOI_MARKER);
reset();
byte[] header = new byte[headerLen];
readFully(header);
try {
mContentLength = parseContentLength(header);
} catch (NumberFormatException nfe) {
mContentLength = getEndOfSeqeunce(this, EOF_MARKER);
}
reset();
byte[] frameData = new byte[mContentLength];
skipBytes(headerLen);
readFully(frameData);
return BitmapFactory.decodeStream(new ByteArrayInputStream(frameData));
}
}
so I converted that (actually create a c# wrapper) with Binding Library project.
but although I followed the Sample code tutorial of this project as following:
The sample itself:
public class MjpegSample extends Activity {
private MjpegView mv;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//sample public cam
String URL = "http://webcam5.hrz.tu-darmstadt.de/axis-cgi/mjpg/video.cgi?resolution=320x240";
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mv = new MjpegView(this);
setContentView(mv);
mv.setSource(MjpegInputStream.read(URL));
mv.setDisplayMode(MjpegView.SIZE_BEST_FIT);
mv.showFps(true);
}
What I have Done in Monodroid:
namespace AndroidApplication8
{
[Activity(Label = "AndroidApplication8", MainLauncher = true, Icon = "#drawable/icon")]
public class Activity1 : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
String URL = "rtsp://192.168.1.3/Mjpeg/video.cgi";
var mv = new MjpegView(this);
SetContentView(mv);
**mv.SetSource(MjpegInputStream.Read(URL));
mv.SetDisplayMode(MjpegView.SizeBestFit);
mv.StartPlayback();
}
}
}
but it gives me an error in the line indicated with ** when it wants to execute MjpegInputStream.Read()
and it jumps to the class converted from the native Java files without any more information.
You should check your video type.For example if your video encoding is compressed over there(before getting to your android device) you should encode it before put it into your browser.This could let you write a code in java for example to verify the incoming stream from cameras first(don't use build-in browser of android) and then decode it manually.
Good luck!

Why is my C# application code not working with my GUI? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
Ok so I am adding on to my last project, where I created a shark race. Everything ran smoothly, and then it got fancy.
Here are the requirements:
1) Declare all of the instance variables to be public properties defined with get and set
accessor methods along with corresponding private backing fields.
2) Remove the MyBet instance variable from the Guy class and instead provide an
array within the Form1 class that holds each Bet instance. The betting parlor should
now allow for each Guy to place multiple bets. However, the Amount of each Bet
should be deducted from the Cash property of each Guy at the time the Bet is made.
Winnings are thus only positive quantities that are paid out after the race.
3) Have a scoreboard (or some type of visual display) that indicates the order in which
each racer finished, allowing for the possibility that there are ties for 1st, 2nd, or 3rd
places.
I'm getting about 50 of the same error, and it seems like they are all very quick fixes, but for some reason I can't figure them out. Thanks in advance!
With that in mind, here are my forms:
Forms Class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace project1
{
public partial class Game : Form
{
private Shark[] sharks;
private Guy[] guys;
private Guy selectedGuy;
private Bet[] bets;
private int[] winners = new int[4];
public Game()
{
InitializeComponent();
Random moreRandom = new Random();
int start = myTrack.Location.X;
int finish = myTrack.Width - 65;
sharks = new Shark[4]
{
new Shark() {myRandom = moreRandom, myPictureBox = myShark1, myPBStart = start, trackLength = finish},
new Shark() {myRandom = moreRandom, myPictureBox = myShark2, myPBStart = start, trackLength = finish},
new Shark() {myRandom = moreRandom, myPictureBox = myShark3, myPBStart = start, trackLength = finish},
new Shark() {myRandom = moreRandom, myPictureBox = myShark4, myPBStart = start, trackLength = finish}
};
guys = new Guy[3]
{
new Guy() {Name="Joe", Moneys=50, MyRB=rbGuy1, GuyLabel=labelBet1},
new Guy() {Name="Bob", Moneys=75, MyRB=rbGuy2, GuyLabel=labelBet2},
new Guy() {Name="Al", Moneys=45, MyRB=rbGuy3, GuyLabel=labelBet3}
};
bets = new Bet[12];
for (int = 0; i<bets.Length; i++)
{
bets[i] = Bet.EmptyBet;
}
selectedGuy = guys[0];
rbGuy1.Tag = guys[0];
rbGuy2.Tag = guys[1];
rbGuy3.Tag = guys[2];
updateGui();
}
private void myChanged(object sender, EventArgs e)
{
selectedGuy = getSelectedGuy(sender);
betterLabel.Text = selectedGuy.Name;
}
private void betAmountValue(object sender, EventArgs e)
{
updateMin();
}
private void bet_Click(object sender, EventArgs e)
{
int bet = (int) betAmount.Value;
int myFish = (int) sharkNumber.Value;
Bet temp = selectedGuy.placeBet(bet,myFish);
if (!temp == Bet.EmptyBet)
{
for (int i = 0; i<3; i++)
{
if (guys[i].Name == selectedGuy.Name)
{
bets[i + (3 * myFish)] = temp;
}
}
/*for (int = 0; i<bets.Length, i++)
{
bets[i] = temp;
}*/
}
//selectedGuy.placeBet(bet, myFish);
updateGui();
}
private void raceBtn_Click(object sender, EventArgs e)
{
betBtn.Enabled = false;
Application.DoEvents();
//bool noWinner = true;
Random rand = new Random();
/*int winner = rand.Next(1,5);
showWinner(winner-1);
collectBets(winner-1);
*/
for(int i=0; i<4; i++)
winners[i] = 0;
for(int i=0; i<4; i++)
{
bool placed = false;
int temp;
while (!placed)
{
temp = rand.Next(0,4);
if (winners[temp] == 0)
{
winners[temp] = i;
placed = true;
}
}
}
showWinner(winners[0] - 1);
collectBets(winners[0] - 1);
/*while(noWinner)
{
for (int fish = 0; fish < sharks.Length; fish++)
{
Application.DoEvents();
if(sharks[fish].Swim())
{
showWinner(fish);
collectBets(fish);
noWinner = false;
}
}
}*/
updateGui();
betBtn.Enabled = true;
}
private void showWinner(int fish)
{
MessageBox.Show(string.Format("Winner Winner People Dinner! \nShark {0} won!", fish + 1));
}
private void collectBets(int fish)
{
for (int guyNumber = 0; guyNumber < guys.Length; guyNumber++)
{
guys[guyNumber].collect(betTotal(), winningSharkTotal());
guys[guyNumber].resetBet();
}
}
private void updateMin()
{
minBetLabel.Text = string.Format("Minimum bet: 5 bucks", betAmount.Value);
}
private Guy getSelectedGuy(object sender)
{
RadioButton rb = (RadioButton)sender;
return (Guy)rb.Tag;
}
private void updateGui()
{
for (int guyNumber = 0; guyNumber < guys.Length; guyNumber++)
{
guys[guyNumber].updateLabels();
}
for (int fish = 0; fish < sharks.Length; fish++)
{
sharks[fish].startPosition();
}
/*betTable1 = bets[0];
betTable2 = bets[1];
betTable3 = bets[2];*/
bet1_1.Text = string.Format(bets[0].Amount);
bet1_2.Text = bets[1].Amount;
bet1_3.Text = bets[2].Amount;
bet2_1.Text = bets[3].Amount;
bet2_2.Text = bets[4].Amount;
bet2_3.Text = bets[5].Amount;
bet3_1.Text = bets[6].Amount;
bet3_2.Text = bets[7].Amount;
bet3_3.Text = bets[8].Amount;
bet4_1.Text = bets[9].Amount;
bet4_2.Text = bets[10].Amount;
bet4_3.Text = bets[11].Amount;
updateMin();
firstWinner.Text = winners[0];
secondWinner.Text = winners[1];
thirdWinner.Text = winners[2];
fourthWinner.Text = winners[3];
}
private int betTotal()
{
int Result = 0;
for (int i=0; i<bets.Length; i++)
{
Result += bets[i].Amount;
}
return Result;
}
private int winningSharkTotal(int Winner)
{
int Result = 0;
for (int i = 0; i<3; i++)
{
Result += bets[i+(winner*3)];
}
return Result;
}
}
}
Sharks Class:
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace project1
{
public class Shark
{
public int myPBStart; // Where the PictureBox starts
public int trackLength; // How long the racetrack is
public PictureBox myPictureBox = null; // The PictureBox object
public int location = 0; // My location on the racetrack
public Random myRandom; // An instance of Random
public Shark()
{
location = 0;
myPictureBox = new PictureBox();
myRandom = new Random();
trackLength = 100;
myPBStart = 0;
}
public bool Swim()
{
int distance = myRandom.Next(1, 4);
location += distance;
movePB(distance);
return location > trackLength;
}
private void movePB(int distance)
{
Point p = myPictureBox.Location;
p.X += distance;
myPictureBox.Location = p;
}
public void startPosition()
{
location = myPBStart;
Point p = myPictureBox.Location;
p.X = location;
myPictureBox.Location = p;
}
}
}
Guy Class:
using System.Windows.Forms;
namespace project1
{
public class Guy
{
private string myName;
//public Bet myBet;
private int cash;
// The last two fields are the the guy's GUI controls on the form
private RadioButton myRadioButton;
private Label myLabel;
const int minBet = 5;
const int maxBet = 15;
public Guy()
{
//myBet = emptyBet();
//myBet = new Bet() { amount = 0, fish = 0, better = this };
}
public void updateLabels()
{
get{
// Set my label to my bet's description and its label
myLabel.Text = myBet.Description();
// cash radio buttons
myRadioButton.Text = radioButtonText();
}
}
public void resetBet()
{
// reset my bet to 0
myBet = Bet.EmptyBet;
}
public string Name{
get{
return myName;
}
}
public int Moneys
{
get
{
return cash;
}
}
public RadioButton MyRB
{
get
{
return myRadioButton;
}
}
public Label GuyLabel
{
get
{
return myLabel;
}
}
public Bet placeBet(int amount, int fish)
{
if (amount > cash || amount < minBet || amount > maxBet)
{
return Bet.EmptyBet;
//return false;
}
cash -= amount;
return new Bet() {Amount=amount, Fish=fish, better=this};
//return true;
}
public void collect(int pool, int sharkPool)
{
get{
return cash += myBet.payout(pool, sharkPool);
}
}
private string radioButtonText()
{
return string.Format("{0} has {1} bucks", myName, cash);
}
}
}
Bet Class:
namespace project1
{
public class Bet
{
private int amount; // The amount of cash that was bet
private int fish; // The number of the shark the bet is on.
public Guy better; // The guy who placed the bet
public static Bet EmptyBet{
get
{
return new Bet() { amount = 0, fish = 0, better = this };
}
}
public string Description
{
get
{
if (noBet())
{
return string.Format("{0} hasn't placed a bet", better.Name);
}
else
{
return string.Format("{0} bets {1} bucks on shark #{2}", better.Name, amount, fish);
}
}
}
public int payout(int pool, int sharkPool)
{
get{
return ((pool * (0.85))/sharkPool) * amount;
/*if (myShark(pool))
{
return amount;
}
else
{
return -amount;
}*/
}
}
/*private bool myShark(int winner)
{
return winner == fish;
}*/
private bool noBet()
{
return amount == 0;
}
public int Amount
{
get
{
return amount;
}
}
public int Fish
{
get
{
return fish;
}
}
}
}
You are confusing the concept of a method and a property. First remove the get { } from you methods and then consider whether void is the right return type. From the looks of it you are returning some sort of decimal value.
public void collect(int pool, int sharkPool)
{
get{
return cash += myBet.payout(pool, sharkPool);
}
}
In the following code, by including the literal 0.85 the resulting value will have type double. The return type of the method is int.
public int payout(int pool, int sharkPool)
{
get{
return ((pool * (0.85))/sharkPool) * amount;
/*if (myShark(pool))
{
return amount;
}
else
{
return -amount;
}*/
}
}
As I mentioned previously, remove the get and mark the return type as double.
public double payout(int pool, int sharkPool)
{
return ((pool * (0.85))/sharkPool) * amount;
}
There is more but I think you have bigger fish to fry. I would go back and review the fundamentals of the C# syntax and try to get a better understanding of numeric data types.
When working with currency you really need to use decimal.
Chaos is correct (and props for seeing what I overlooked). It also looks like there are some type conversion errors being generated from assigning Bet.Amount to a TextBox. Call ToString() on your integer values, and these errors should go away.
Error 42 Cannot implicitly convert
type 'int' to 'string'
And please remember that UI elements (like labels, radio buttons, picture boxes) do not belong on business objects like Guys or Sharks. This is design decision that is far more fundamental than fixing a few compiler errors (though I'm sure it doesn't seem that way at the moment).

Categories