I am working on a Xamarin.Forms map screen and i need to implement an overlay that contains circle around a pin on the map, as shown on the screenshot.
The problem is on the IOS version. I cannot move the map inside the circle. The android version works just fine.
Repo for the project: https://github.com/CrossGeeks/OverlaySample
Any help with the custom renderer would be appreciated!!!
using System;
using System.ComponentModel;
using CoreGraphics;
using OverlaySample.Controls;
using OverlaySample.iOS.Renderers;
using OverlaySample.iOS.Views;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(OverlayView), typeof(OverlayViewRenderer))]
namespace OverlaySample.iOS.Renderers
{
public class OverlayViewRenderer : ViewRenderer<OverlayView, NativeOverlayView>
{
protected override void OnElementChanged(ElementChangedEventArgs<OverlayView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
SetNativeControl(new NativeOverlayView()
{
ContentMode= UIViewContentMode.ScaleToFill
});
}
if (e.NewElement != null)
{
Control.Opacity = (float)Element.OverlayOpacity;
Control.ShowOverlay = Element.ShowOverlay;
Control.OverlayBackgroundColor = Element.OverlayBackgroundColor.ToUIColor();
Control.OverlayShape = Element.Shape;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == OverlayView.OverlayOpacityProperty.PropertyName)
{
Control.Opacity = (float)Element.OverlayOpacity;
Control.UpdateOpacity();
}
else if (e.PropertyName == OverlayView.OverlayBackgroundColorProperty.PropertyName)
{
Control.OverlayBackgroundColor = Element.OverlayBackgroundColor.ToUIColor();
Control.UpdateFillColor();
}
else if (e.PropertyName == OverlayView.ShapeProperty.PropertyName)
{
Control.OverlayShape = Element.Shape;
Control.UpdatePath();
}
else if (e.PropertyName == OverlayView.ShowOverlayProperty.PropertyName)
{
Control.ShowOverlay = Element.ShowOverlay;
}
}
bool rendered = false;
public override void LayoutSubviews()
{
base.LayoutSubviews();
if(!rendered && Control.ShowOverlay)
{
Control.AddOverlayLayer();
rendered = true;
}
}
}
}
And the OverlaySample.iOS.Views:
namespace OverlaySample.iOS.Views
{
public class NativeOverlayView : UIView
{
bool showOverlay = true;
public bool ShowOverlay
{
get { return showOverlay; }
set
{
showOverlay = value;
if (showOverlay)
AddOverlayLayer();
else
RemoveOverlayLayer();
}
}
CAShapeLayer overlayLayer = null;
public float Opacity { get; set; } = 0.5f;
public UIColor OverlayBackgroundColor { get; set; } = UIColor.Clear;
public OverlayShape OverlayShape { get; set; } = OverlayShape.Circle;
UIBezierPath GetHeartOverlayPath(CGRect originalRect, float scale)
{
var scaledWidth = (originalRect.Size.Width * scale);
var scaledXValue = ((originalRect.Size.Width) - scaledWidth) / 2;
var scaledHeight = (originalRect.Size.Height * scale);
var scaledYValue = ((originalRect.Size.Height) - scaledHeight) / 2;
var scaledRect = new CGRect(x: scaledXValue, y: scaledYValue, width: scaledWidth, height: scaledHeight);
UIBezierPath path = new UIBezierPath();
path.MoveTo(new CGPoint(x: originalRect.Size.Width / 2, y: scaledRect.Y + scaledRect.Size.Height));
path.AddCurveToPoint(new CGPoint(x: scaledRect.X, y: scaledRect.Y + (scaledRect.Size.Height / 4)),
controlPoint1: new CGPoint(x: scaledRect.X + (scaledRect.Size.Width / 2), y: scaledRect.Y + (scaledRect.Size.Height * 3 / 4)),
controlPoint2: new CGPoint(x: scaledRect.X, y: scaledRect.Y + (scaledRect.Size.Height / 2)));
path.AddArc(new CGPoint(scaledRect.X + (scaledRect.Size.Width / 4), scaledRect.Y + (scaledRect.Size.Height / 4)),
(scaledRect.Size.Width / 4),
(nfloat)Math.PI,
0,
true);
path.AddArc(new CGPoint(scaledRect.X + (scaledRect.Size.Width * 3 / 4), scaledRect.Y + (scaledRect.Size.Height / 4)),
(scaledRect.Size.Width / 4),
(nfloat)Math.PI,
0,
true);
path.AddCurveToPoint(new CGPoint(x: originalRect.Size.Width / 2, y: scaledRect.Y + scaledRect.Size.Height),
controlPoint1: new CGPoint(x: scaledRect.X + scaledRect.Size.Width, y: scaledRect.Y + (scaledRect.Size.Height / 2)),
controlPoint2: new CGPoint(x: scaledRect.X + (scaledRect.Size.Width / 2), y: scaledRect.Y + (scaledRect.Size.Height * 3 / 4)));
path.ClosePath();
return path;
}
UIBezierPath GetCircularOverlayPath()
{
int radius = (int)(Bounds.Width / 2) - 20;
UIBezierPath circlePath = UIBezierPath.FromRoundedRect(new CGRect(Bounds.GetMidX() - radius, Bounds.GetMidY() - radius, 2.0 * radius, 2.0 * radius), radius);
circlePath.ClosePath();
return circlePath;
}
public void AddOverlayLayer()
{
UIBezierPath path = UIBezierPath.FromRoundedRect(new CGRect(Frame.X, Frame.Y, this.Frame.Width, this.Frame.Height), 0);
path.AppendPath(OverlayShape == OverlayShape.Circle ? GetCircularOverlayPath() : GetHeartOverlayPath(path.Bounds, 0.95f));
path.UsesEvenOddFillRule = true;
CAShapeLayer fillLayer = new CAShapeLayer();
fillLayer.Path = path.CGPath;
fillLayer.FillRule = CAShapeLayer.FillRuleEvenOdd;
fillLayer.FillColor = OverlayBackgroundColor.CGColor;
fillLayer.Opacity = Opacity;
overlayLayer = fillLayer;
Layer.AddSublayer(fillLayer);
}
public void UpdatePath()
{
UIBezierPath path = UIBezierPath.FromRoundedRect(new CGRect(Frame.X, Frame.Y, this.Frame.Width, this.Frame.Height), 0);
path.AppendPath(OverlayShape == OverlayShape.Circle ? GetCircularOverlayPath() : GetHeartOverlayPath(path.Bounds, 0.95f));
overlayLayer.Path = path.CGPath;
}
public void UpdateOpacity()
{
if(overlayLayer!=null)
overlayLayer.Opacity = Opacity;
}
public void UpdateFillColor()
{
if (overlayLayer != null)
overlayLayer.FillColor = OverlayBackgroundColor.CGColor;
}
public void RemoveOverlayLayer()
{
//if(Layer.Sublayers!=null)
//foreach (var l in Layer.Sublayers)
//{
// l.RemoveFromSuperLayer();
//}
overlayLayer?.RemoveFromSuperLayer();
}
}
}
Related
I want to draw millimeter paper into a pdf, but when I measure the printed document I'm a bit off (drawn cm < 1 cm). I'm using the size of an A4 Paper (210 * 297) and the pageWidth and pageHeight to calculate the pixel per mm (used the average of both hoping this would work). I also tried different option when printing the document (with & without margin etc.), but this didn't work as well.
public class TestPrint extends Application {
protected static final float DINA4_IN_MM_WIDTH = 210;
protected static final float DINA4_IN_MM_HEIGHT = 297;
protected static final int LEFTSIDE = 35;
protected static final int TEXT_FONT_SIZE = 11;
protected static final int TOP_MARGIN = 60;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
File file = new File("test.pdf");
double windowWidth = 600;
double windowHeight = 1000;
float x = LEFTSIDE;
PDFont font = PDType1Font.TIMES_ROMAN;
PDPage page = new PDPage(PDRectangle.A4);
PDRectangle pageSize = page.getMediaBox();
PDDocument mainDocument = new PDDocument();
mainDocument.addPage(page);
float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * TEXT_FONT_SIZE;
float y = pageSize.getHeight() - stringHeight / 1000f - TOP_MARGIN;
float pixelPerMM = (pageSize.getWidth() / DINA4_IN_MM_WIDTH + pageSize.getHeight() / DINA4_IN_MM_HEIGHT) / 2;
float displayW = 520;
float displayH = 300;
try {
PDPageContentStream contents = new PDPageContentStream(mainDocument, page, AppendMode.APPEND, true);
drawBackgroundRaster(contents, x, y, displayW, displayH, pixelPerMM);
contents.close();
mainDocument.save(file);
ImageView imgView = getImageViewFromDocument(mainDocument, windowHeight);
VBox vBox = new VBox(imgView);
Scene scene = new Scene(vBox, windowWidth, windowHeight);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
// draw millimeter paper with dots, two boxes shall be 1cm
private void drawBackgroundRaster(PDPageContentStream contents, float x, float y, float displayW, float displayH,
float pixelPerMM) throws IOException {
// rasterColor = grey
Color rasterColor = new Color(175, 175, 175);
contents.setStrokingColor(rasterColor);
float dotSize = 0.5f;
// draw vertical lines
for (int i = 0; i <= displayW; i++) {
float xPos = x + i * pixelPerMM;
if (xPos > displayW + x) {
break;
}
contents.moveTo(xPos, y);
if (i % 5 == 0) {
contents.setLineDashPattern(new float[] {}, 0);
contents.lineTo(xPos, y - displayH);
}
contents.stroke();
}
// draw dots and horizontal lines
for (int i = 0; i <= displayH; i++) {
float yPos = y - i * pixelPerMM;
if (yPos < y - displayH) {
break;
}
contents.moveTo(x, yPos);
if (i % 5 == 0) {
contents.setLineDashPattern(new float[] {}, 0);
contents.lineTo(x + displayW, yPos);
} else {
contents.setLineDashPattern(new float[] { dotSize, pixelPerMM - dotSize }, dotSize / 2);
contents.lineTo(x + displayW, yPos);
}
contents.stroke();
}
contents.setLineDashPattern(new float[] {}, 0);
contents.moveTo(x, y);
contents.lineTo(x + displayW, y);
contents.lineTo(x + displayW, y - displayH);
contents.lineTo(x, y - displayH);
contents.lineTo(x, y);
contents.stroke();
}
private ImageView getImageViewFromDocument(PDDocument mainDocument, double windowHeight) throws IOException {
PDFRenderer pdfRenderer = new PDFRenderer(mainDocument);
BufferedImage bim = pdfRenderer.renderImageWithDPI(0, 150, ImageType.RGB);
Image image = SwingFXUtils.toFXImage(bim, null);
ImageView imageView = new ImageView(image);
double scaleFactor = windowHeight / imageView.getImage().getHeight();
double zoomFactor = scaleFactor * 2d * 2.55d / 3;
double width = imageView.getImage().getWidth() * zoomFactor;
double height = imageView.getImage().getHeight() * zoomFactor;
imageView.setFitWidth(width);
imageView.setFitHeight(height);
return imageView;
}
}
Hi Guys, I'm building an app that has an Entry similar to that of tinder, does anyone have an idea on how I can achieve this. I tried creating multiple entries and move focus on the text entered but deleting is the issue as TextChaned method is only called when there is text
In Xamarin.Forms , you can Custom a Entry Render View in iOS to implement it .
Create a custom Entry :
public class CustomEntry : Entry
{
}
Then in Native iOS, create a CustomEntryRenderer :
public class CustomEntryRenderer : EntryRenderer
{
private UITextField textField;
int numberCount = 6;
nfloat itemMargin =20;
List<UILabel> labels = new List<UILabel>();
List<UIView> lines = new List<UIView>();
UIControl maskView = new UIControl();
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
textField = (UITextField)this.Control;
//textField.ReturnKeyType = UIReturnKeyType.Done;
textField.KeyboardType = UIKeyboardType.NumberPad;
textField.AutocapitalizationType = UITextAutocapitalizationType.None;
textField.TextColor = UIColor.Clear;
textField.TintColor = UIColor.Clear;
textField.EditingChanged += TextField_EditingChanged;
UIButton maskView = new UIButton();
maskView.BackgroundColor = UIColor.White;
maskView.TouchUpInside += MaskView_TouchUpInside;
textField.AddSubview(maskView);
this.maskView = maskView;
for (int i = 0; i < numberCount; i++)
{
UILabel label = new UILabel();
label.TextAlignment = UITextAlignment.Center;
label.TextColor = UIColor.DarkTextColor;
label.Font = UIFont.FromName("PingFangSC-Regular", 41);
textField.AddSubview(label);
labels.Add(label);
}
for(int i = 0; i < numberCount; i++)
{
UIView line = new UIView();
line.BackgroundColor = UIColor.Purple;
textField.AddSubview(line);
lines.Add(line);
}
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
nfloat temp = textField.Bounds.Size.Width - (itemMargin * (numberCount - 1));
nfloat w = temp / numberCount;
nfloat x = 0;
for(int i = 0; i < labels.Count; i++)
{
x = i * (w + itemMargin);
UILabel label = labels[i];
label.Frame = new CGRect(x, 0, w, textField.Bounds.Size.Height);
UIView line = lines[i];
line.Frame = new CGRect(x, textField.Bounds.Size.Height - 1, w, 1);
}
maskView.Frame = textField.Bounds;
}
private void MaskView_TouchUpInside(object sender, EventArgs e)
{
textField.BecomeFirstResponder();
}
private void TextField_EditingChanged(object sender, EventArgs e)
{
if(textField.Text.Length > numberCount)
{
//Range range = new Range(0, numberCount);
textField.Text = textField.Text.Substring(0, numberCount);
}
for(int i = 0; i < numberCount; i++)
{
UILabel label = labels[i];
if(i< textField.Text.Length)
{
label.Text = textField.Text.Substring(i, 1);
}
else
{
label.Text = "";
}
}
if (textField.Text.Length >= numberCount)
{
textField.ResignFirstResponder();
}
}
}
Finally , you can use it in Xaml :
<ProjectNameSpace:CustomEntry x:Name="customEntry" WidthRequest="300" />
The effect :
I wrote a Snake Game , when it hit it's tail , it will be Game Over and throw an alert. I set a Button in stage of my alert for new game , and i want to use that to run my cod again at first. is there any method or something...
It's my alert class
class alart {
public static void Game_over_alart(int dom) {
dom = (dom - 9) * 10 ;
Label sdom = new Label(Integer.toString(dom));
Stage window = new Stage();
window.setTitle("Game_Over");
Label gameOver = new Label("Game Over");
Label scor = new Label("SCORE : ");
Label best = new Label("BEST : ");
Text newgame = new Text("NEW GAME");
HBox hbox1 = new HBox(2, scor , sdom );
HBox hbox2 = new HBox(2, best);
VBox vbox = new VBox(2, hbox1, hbox2);
gameOver.setStyle(""
+ "-fx-alignment: top;"
+ "-fx-font-size: 40px;"
+ "-fx-font-style: italic;"
+ "-fx-font-weight: bold;"
+ "-fx-font-family: fantasy;"
+ "-fx-text-fill: lightgrey ;");
// + "-fx-background-color: gray");
DropShadow d = new DropShadow(5, Color.BLACK);
ScaleTransition st=new ScaleTransition(Duration.millis(100),newgame);
st.setToX(1.1);
st.setToY(1.1);
st.setFromX(1);
st.setFromY(1);
//st.setAutoReverse(true);
// st.setCycleCount(Animation.INDEFINITE);
gameOver.setEffect(d);
BorderPane b = new BorderPane();
b.setTop(gameOver);
b.setCenter(vbox);
b.setBottom(newgame);
gameOver.setAlignment(Pos.CENTER);
Scene s = new Scene(b, 400, 200);
window.setScene(s);
window.show();
window.setResizable(false);
newgame.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
}
});
newgame.addEventHandler(MouseEvent.MOUSE_ENTERED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event1) {
st.play();
}
});
newgame.addEventHandler(MouseEvent.MOUSE_EXITED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event1) {
st.setFromX(1.1);
st.setFromY(1.1);
st.setToX(1);
st.setToY(1);
}
});
}
}
and it's the whole of my code
/**
* Created by Nadia on 12/31/2015.
*/
import javafx.animation.Animation;
import javafx.animation.AnimationTimer;
import javafx.animation.ScaleTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
import sun.jvm.hotspot.debugger.cdbg.Sym;
import javax.swing.text.StyledEditorKit;
import java.util.ArrayList;
public class Main_Snake extends Application{
Canvas canvas = new Canvas(399, 599);
Rectangle round = new Rectangle(0 ,0 , 400 , 600 );
B_Part snake = new Snake();
B_Part apple = new Apple();
B_Part mane = new Mane();
#Override
public void start(Stage primaryStage) throws Exception {
round.setStroke(Color.BLACK);
round.setFill(Color.WHITE);
StackPane ss = new StackPane();
ss.getChildren().addAll(round, canvas);
BorderPane b = new BorderPane();
b.setBottom(ss);
Scene scene = new Scene(b, 410, 700);
primaryStage.setScene(scene);
primaryStage.setTitle ( "Snake" );
primaryStage.show();
primaryStage.setResizable(false);
play();
}
public void play() {
AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
#Override
public void handle(long now) {
if (now - lastUpdate >= 20_000_000) { // payin avordane sor#
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
try {
for ( int i = 0 ; i < 5 ; i++)
mane.Move(canvas.getScene());
} catch (Game_Over_Exception e) {
}finally {
mane.Drow(canvas);
}
try {
apple.Move(canvas.getScene());
}catch (Exception e) {
}finally {
apple.Drow(canvas);
}
try {
snake.Move(canvas.getScene());
} catch (Game_Over_Exception e) {
stop();
alart.Game_over_alart(snake.X.size());
}finally {
snake.Drow(canvas); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast
}
lastUpdate = now; // sor#
}
}
};
timer.start();
}
}
abstract class B_Part {
boolean goNorth = true, goSouth = false, goWest = false, goEast = false; ///////////////////////////////////////////////////////
static int GM = 0 ;
int Mx , My ;
static ArrayList<Integer> Mane_x = new ArrayList<>();
static ArrayList<Integer> Mane_y = new ArrayList<>();
static int x, y ; // marbut be apple
static int j = 0;
// int gm_ov = 0; // vase game over shodan
static ArrayList<Integer> X = new ArrayList<>();
static ArrayList<Integer> Y = new ArrayList<>();
static int Domx1 =400 , Domy1 =390 ;
static int Domx2 =400, Domy2 =400 ;
abstract public void Drow(Canvas canvas);
abstract public void Move(Scene scene)throws Game_Over_Exception;
void Point() {
if (X.get(0) == x && Y.get(0) == y)
j = 0;
}
void Game_Over() {
for (int i = 1 ; i < X.size() ; i ++) { // inke mokhtasate sare mar tu mokhtasate tanesh hast ya na
if (X.get(0).equals(X.get(i)) && Y.get(0).equals(Y.get(i))) {
GM = 1;
}
}
for (int i = 0 ; i < Mane_x.size() ; i ++) { // inke mokhtasate sare mar be mane hast ya na
if (X.get(0).equals(Mane_x.get(i)) && Y.get(0).equals(Mane_y.get(i))) {
GM = 1;
}
}
}
}
class Apple extends B_Part {
#Override
public void Move(Scene scene) {
if (j == 0) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
x = (int) ( Math.random() * 390 + 1 );
y = (int) ( Math.random() * 590 + 1 );
} while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0);
/*
inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune
y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab
haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide
*/
j = 1;
}
}
#Override
public void Drow(Canvas canvas) {
DropShadow dd = new DropShadow(20,Color.RED);
GraphicsContext a = canvas.getGraphicsContext2D();
a.setFill(Color.RED);
a.setEffect(dd);
a.fillRect( x , y , 9 ,9);
a.setEffect(null);
}
}
class Snake extends B_Part {
Snake() { //cunstructor
X.add(400);
Y.add(300);
X.add(400);
Y.add(310);
X.add(400);
Y.add(320);
X.add(400);
Y.add(330);
X.add(400);
Y.add(340);
X.add(400);
Y.add(350);
X.add(400);
Y.add(360);
X.add(400);
Y.add(370);
X.add(400);
Y.add(380);
}
#Override
public void Drow(Canvas canvas) {
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
// keshidane mar (body yeki ezafe tar az adade morabaA mide)
for (int i = X.size() - 1; i >= 0; i--) {
gc.fillRect(X.get(i), Y.get(i), 9, 9);
gc.setStroke(Color.WHITE);
}
}
#Override
public void Move(Scene scene) throws Game_Over_Exception {
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent small) {
switch (small.getText()) {
case "W":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "w":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "S":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "s":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "A":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "a":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "D":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
case "d":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
/* scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
switch (e.getCode()) {
case UP:
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case DOWN:
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case LEFT:
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case RIGHT:
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
*/
Domx1 = X.get(X.size() - 1);
Domy1 = Y.get(Y.size() - 1);
for (int z = X.size() - 1; z > 0; z--) {
X.remove(z);
X.add(z, X.get(z - 1));
Y.remove(z);
Y.add(z, Y.get(z - 1));
}
if (goNorth) {
Y.add(0, Y.get(0) - 10);
Y.remove(1);
}
if (goSouth) {
Y.add(0, Y.get(0) + 10);
Y.remove(1);
}
if (goEast) {
X.add(0, X.get(0) + 10);
X.remove(1);
}
if (goWest) {
X.add(0, X.get(0) - 10);
X.remove(1);
}
Point(); // emtiaz gerefte
if (j == 0) {
X.add(Domx1);
Y.add(Domy1);
X.add(Domx2);
Y.add(Domy2);
Domx2 = Domx1;
Domy2 = Domy1;
System.out.println();
System.out.println("size : "+Mane_x.size() );
System.out.print(" clear : " );
Mane_x.clear();
Mane_y.clear();
System.out.println("size : "+Mane_x.size() );
}
Game_Over();
if ( GM == 1 ) {
throw new Game_Over_Exception("Game Over");
}
if (X.get(0) > 390) {
X.remove(0);
X.add(0, 0);
}
if (X.get(0) < 0) {
X.remove(0);
X.add(0, 400);
}
if (Y.get(0) > 590) {
Y.remove(0);
Y.add(0, 0);
}
if (Y.get(0) < 0) {
Y.remove(0);
Y.add(0, 600);
}
}
}
class Mane extends B_Part{
#Override
public void Drow(Canvas canvas) {
GraphicsContext gc = canvas.getGraphicsContext2D();
for ( int i = 0 ; i < Mane_x.size() ; i++) {
gc.setFill(Color.GRAY);
gc.fillRect(Mane_x.get(i), Mane_y.get(i), 9, 9);
}
//System.out.println(Mane_x.get(i)+" "+Mane_y.get(i));}
}
#Override
public void Move(Scene scene) {
if (j == 0) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
Mx = (int) (Math.random() * 390 + 1);
My = (int) (Math.random() * 590 + 1);
} while (Mx == x && My == y ||
Mane_x.indexOf(Mx) != -1 && Mane_y.get(Mane_x.indexOf(Mx)) == My ||
X.indexOf(Mx) != -1 && Y.get(X.indexOf(Mx)) == My ||
Mx % 10 != 0 || My % 10 != 0
/* Mx == X.get(0) + 10 && My == Y.get(0) || // yeki joloye saresh nayofte (vaghti rast mire)
Mx == X.get(0) - 10 && My == Y.get(0) || // ( vaghti chap mire)
Mx == X.get(0) && My == Y.get(0) + 10 || // yek ta jolo tar az saresh nayofte vaghtti payi
Mx == X.get(0) && My == Y.get(0) - 10*/); // vaghti bala
//sharte chek kardane in ke har maneye random rooye mar ya maneye ghablia nayofte ( sib hamintor )
Mane_x.add(Mx);
Mane_y.add(My);
}
}
}
class Game_Over_Exception extends Exception{
public Game_Over_Exception (String s){
super(s);
}
}
Hand over a restart method to the alert handler. You can do that directly or via interface, e. g.:
public interface GameManager {
public void restart();
}
Your main class must implement that interface:
public class Main_Snake extends Application implements GameManager {
public void restart() {
// TODO: reset playfield & restart game
}
public void play() {
...
try {
snake.Move(canvas.getScene());
} catch (Game_Over_Exception e) {
stop();
alart.Game_over_alart(snake.X.size(), Main_Snake.this);
}
...
}
}
And in your alart class you invoke that method:
class alart {
public static void Game_over_alart(int dom, GameManager gameManager) {
...
newgame.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// TODO: close dialog
// restart game
gameManager.restart();
}
});
...
}
}
I have a requirement to create a round corner buttons but I am new to dev express.Do we have any buttons in Dev express 8.2 which supports round corner.With normal button i tried following code but it didnt work.
public class RoundButton : Button
{
protected override void OnResize(EventArgs e)
{
using (var path = new System.Drawing.Drawing2D.GraphicsPath())
{
path.AddEllipse(new Rectangle(0, 0, 80, 30));
this.Region = new Region(path);
}
base.OnResize(e);
}
}
public class RoundButton : Button
{
bool isMouseEnter = false;
GraphicsPath GetRoundPath(RectangleF Rect, int radius)
{
float r2 = radius / 2f;
GraphicsPath GraphPath = new GraphicsPath();
GraphPath.AddArc(Rect.X-1, Rect.Y, radius, radius, 180, 90);
GraphPath.AddLine(Rect.X + r2, Rect.Y, Rect.Width - r2, Rect.Y);
GraphPath.AddArc(Rect.X + Rect.Width - radius, Rect.Y, radius, radius, 271, 90);
GraphPath.AddLine(Rect.Width, Rect.Y + r2, Rect.Width, Rect.Height - r2);
GraphPath.AddArc(Rect.X + Rect.Width - radius - 1,
Rect.Y + Rect.Height - radius, radius, radius, 1, 90);
GraphPath.AddLine(Rect.Width - r2, Rect.Height, Rect.X + r2, Rect.Height);
GraphPath.AddArc(Rect.X, Rect.Y + Rect.Height - radius, radius, radius, 90, 90);
GraphPath.AddLine(Rect.X, Rect.Height - r2, Rect.X, Rect.Y + r2);
// GraphPath.CloseFigure();
return GraphPath;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
RectangleF Rect = new RectangleF(0, 0, this.Width, this.Height);
GraphicsPath GraphPath = GetRoundPath(Rect, 10);
this.Region = new Region(GraphPath);
using (Pen pen = new Pen(System.Drawing.Color.FromArgb(74, 174, 74), 8.25F))
{
if (isMouseEnter)
pen.Color = System.Drawing.Color.FromArgb(88, 208, 88);
pen.Alignment = PenAlignment.Inset;
e.Graphics.DrawPath(pen, GraphPath);
}
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
isMouseEnter = true;
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
isMouseEnter = false;
}
}
In my ASP.NET project, I add a new array item with the help of query string. once the array item added, my client reload the browser,. so the same item add another time. It happens each reload timing.
but i don't want this. any possible to stop this browser reload or stop the same array item?
my url is -
51402/ItemGrid.aspx?id=3035
then id=3035 item added to the array.
My Code in page load event
string query ="";
int array_no;
if (Convert.ToUInt32(GlobalClass.GlobalarrayNo.ToString()) == 0)
{
array_no = 0;
Array.Clear(roomno, 0, roomno.Length);
}
else
{
array_no = Convert.ToInt32(GlobalClass.GlobalarrayNo.ToString());
}
id = Convert.ToInt32(Request.QueryString["id"]);
if (!Page.IsPostBack)
{
// ******* Happy Status ************
decimal happyfromtime = 0;
string happyper="";
string happytotime = "";
query = "SELECT Parameters_Parameter3,Parameters_Parameter2,Parameters_Parameter1,Parameters_Parameter4 FROM MCS_Parameters WHERE Parameters_TYPE ='HAPHOU'";
MySqlConnection connection = new MySqlConnection(GlobalClass.GlobalConnString.ToString());
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
happyfromtime= Convert.ToDecimal(Reader[0].ToString());
happyper=Reader[1].ToString();
happystatus= Convert.ToInt32(Reader[2].ToString());
happytotime = Reader[3].ToString();
}
connection.Close();
string t = GlobalClass.GlobalserverTime.ToString();
t= t.Substring(0,5);
t = t.Replace(":",".");
//ALLTRIM(CurCate.Fb_Item_Creation_HappyhoursStatus)='Yes'
if ((Convert.ToDecimal(t) > Convert.ToDecimal(happyfromtime)) && (Convert.ToDecimal(t) < Convert.ToDecimal(happytotime)) && (happystatus == 1))
{
tHappy_Status = 1;
}
if (GlobalClass.GlobalservedAt == "RST")
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_RestaurantPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus,a.Fb_Item_Creation_HappyhoursStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
else if (GlobalClass.GlobalservedAt == "BAR")
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_BarPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus,a.Fb_Item_Creation_HappyhoursStatus,a.Fb_Item_Creation_HappyhoursStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
else
{
query = "select a.Fb_Item_Creation_ItemDescription, a.Fb_Item_Creation_RoomPrice, a.Fb_Item_Creation_ItemCode, a.Fb_Item_Creation_TaxStatus, "
+ "a.Fb_Item_Creation_VatPercentage, a.Fb_Item_Creation_ServicechargeStatus, a.Fb_Item_Creation_SurchargeStatus, a.Fb_Item_Creation_DiscountStatus,"
+ "a.FB_Item_ID, b.Fb_Category_Stock, b.Fb_Category_Name,a.Fb_Item_Creation_ModifierStatus from fb_item_creation a, fb_category b "
+ "where a.FB_Item_ID = '" + id + "' and a.Fb_Item_Creation_DeleteStatus=0 and "
+ "a.Fb_Item_Creation_OutletId='" + GlobalClass.GlobaloutletId + "' "
+ "and a.Fb_Item_Creation_ItemGroupId='" + GlobalClass.GlobalitemGroupId + "' and b.Fb_Category_DeleteStatus=0 and "
+ "b.Fb_Category_Id = a.Fb_Item_Creation_ItemCategoryId";
}
connection = new MySqlConnection(GlobalClass.GlobalConnString.ToString());
command = new MySqlCommand(query, connection);
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
roomno[array_no, 0] = Reader[0].ToString(); // Fb_Item_Creation_ItemDescription
if (GlobalClass.GlobalopenCode == "OPEN")
{
roomno[array_no, 0] = GlobalClass.GlobalopenDes.ToString(); // Fb_Item_Creation_ItemDescription
roomno[array_no, 1] = GlobalClass.GlobalopenRate.ToString(); // Fb_Item_Creation_RoomPrice
roomno[array_no, 2] = GlobalClass.GlobalopenQty.ToString(); // Qty
roomno[array_no, 3] = Reader[2].ToString(); // Fb_Item_Creation_ItemCode
roomno[array_no, 4] = Reader[3].ToString(); // Fb_Item_Creation_TaxStatus
roomno[array_no, 5] = Reader[4].ToString(); // Fb_Item_Creation_VatPercentage
roomno[array_no, 6] = Reader[5].ToString(); // Fb_Item_Creation_ServicechargeStatus
roomno[array_no, 7] = Reader[6].ToString(); // Fb_Item_Creation_SurchargeStatus
roomno[array_no, 8] = Reader[7].ToString(); // Fb_Item_Creation_DiscountStatus
roomno[array_no, 9] = Reader[8].ToString(); // FB_Item_ID
roomno[array_no, 10] = Reader[9].ToString(); // Fb_Category_Stock
roomno[array_no, 11] = Reader[10].ToString(); // Fb_Category_Name
roomno[array_no, 12] = Reader[1].ToString(); // Total = rate * qty
roomno[array_no, 13] = Reader[11].ToString(); //Fb_Item_Creation_ModifierStatus
roomno[array_no, 14] = ""; //Fb_Kot_Item_TouchLine
roomno[array_no, 15] = ""; // UserModifier
roomno[array_no, 16] = Reader[12].ToString(); // HappyHours
array_no++;
GlobalClass.GlobalarrayNo = array_no;
}
else if (roomno[array_no, 0] == "OPEN")
{
Response.Redirect("OpenItem.aspx" + "?id=" + id);
}
else
{
roomno[array_no, 1] = Reader[1].ToString(); // Fb_Item_Creation_RoomPrice
roomno[array_no, 2] = "1"; // Qty
roomno[array_no, 3] = Reader[2].ToString(); // Fb_Item_Creation_ItemCode
roomno[array_no, 4] = Reader[3].ToString(); // Fb_Item_Creation_TaxStatus
roomno[array_no, 5] = Reader[4].ToString(); // Fb_Item_Creation_VatPercentage
roomno[array_no, 6] = Reader[5].ToString(); // Fb_Item_Creation_ServicechargeStatus
roomno[array_no, 7] = Reader[6].ToString(); // Fb_Item_Creation_SurchargeStatus
roomno[array_no, 8] = Reader[7].ToString(); // Fb_Item_Creation_DiscountStatus
roomno[array_no, 9] = Reader[8].ToString(); // FB_Item_ID
roomno[array_no, 10] = Reader[9].ToString(); // Fb_Category_Stock
roomno[array_no, 11] = Reader[10].ToString(); // Fb_Category_Name
roomno[array_no, 12] = Reader[1].ToString(); // Total = rate * qty
roomno[array_no, 13] = Reader[11].ToString(); //Fb_Item_Creation_ModifierStatus
roomno[array_no, 14] = ""; //Fb_Kot_Item_TouchLine
roomno[array_no, 15] = ""; // UserModifier
roomno[array_no, 16] = Reader[12].ToString(); // HappyHours
if ((tHappy_Status == 1) && (roomno[array_no, 16].ToString()=="Yes"))
{
roomno[array_no, 8] = "Yes";
}
array_no++;
GlobalClass.GlobalarrayNo = array_no;
//var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
//nameValues.Set("sortBy", "4");
//string url = Request.Url.AbsolutePath;
//string updatedQueryString = "?" + nameValues.ToString();
//Response.Redirect(url + updatedQueryString);
}
}
connection.Close();
ViewState["btn"] = "1";
ViewState["tot"] = "0";
ViewState["happystatus"] = happystatus;
btn_click = Convert.ToInt32(ViewState["btn"].ToString());
int len = array_no;
while (len > 8)
{
len = len - 8;
tot++;
}
if (len != 0) tot++;
ViewState["tot"] = tot;
fun();
//CreatingTmpModdbf1();
// Modifier Text
int seq = Convert.ToInt32(Request.QueryString["seq"]);
string text = Request.QueryString["text"];
if (text != null)
{
roomno[seq - 1, 15] = text;
}
}
!postback is not help to avoid my problem.
static class GlobalClass
{
private static string myConnString1 = "";
private static int userId = 0;
private static string userName = "";
private static int outletId = 0;
private static int itemGroupId = 0;
private static DateTime serverDate;
private static string serverTime = "";
private static string tableName = "";
private static string serverdAt = "";
private static int arrayNo = 0;
private static int waiterId = 0;
private static int covers = 0;
private static string kotno = "";
public static string GlobalConnString
{
get { return myConnString1; }
set { myConnString1 = value; }
}
public static int GlobaluserId
{
get { return userId;}
set { userId = value; }
}
public static string GlobaluserName
{
get { return userName; }
set { userName = value; }
}
public static int GlobaloutletId
{
get { return outletId; }
set { outletId = value; }
}
public static DateTime GlobalserverDate
{
get { return serverDate; }
set { serverDate = value; }
}
public static string GlobalserverTime
{
get { return serverTime; }
set { serverTime = value; }
}
public static string GlobaltableName
{
get { return tableName; }
set { tableName = value; }
}
public static int GlobalitemGroupId
{
get { return itemGroupId; }
set { itemGroupId = value; }
}
public static string GlobalservedAt
{
get { return serverdAt; }
set { serverdAt = value; }
}
public static int GlobalarrayNo
{
get { return arrayNo; }
set { arrayNo = value; }
}
public static int GlobalwaiterId
{
get { return waiterId; }
set { waiterId = value; }
}
public static int Globalcovers
{
get { return covers; }
set { covers = value; }
}
public static string GlobalkotNo
{
get { return kotno ; }
set { kotno = value; }
}
public static string staffId = "";
public static string staffCategoryId = "";
public static string GlobalstaffId
{
get { return staffId; }
set { staffId = value; }
}
public static string GlobalstaffCategoryId
{
get { return staffCategoryId; }
set { staffCategoryId = value; }
}
public static string openCode = "";
public static string openDes = "";
public static string GlobalopenCode
{
get { return openCode; }
set { openCode = value; }
}
public static string GlobalopenDes
{
get { return openDes; }
set { openDes = value; }
}
public static string openQty = "";
public static string openRate = "";
public static string GlobalopenQty
{
get { return openQty; }
set { openQty = value; }
}
public static string GlobalopenRate
{
get { return openRate; }
set { openRate = value; }
}
}
I assume that your array is static/shared. Static variables are shared across the whole app domain and all threads. Hence every user uses the same variable.
Don't use static variables therefor, instead of persisting the array you should use the querystring again.
If this was a wrong assumption you should show us your code
After adding item you can redirect to another page. For example 51402/ItemGrid.aspx
Also using get request to save/edit/delete data is not good idea, better use post.
If you are adding the item to the Array within Page_Load, you may want to wrap the code that adds the item in the following:
If Not Page.IsPostBack Then
//Your array item adding code here
End If
This will prevent the item adding again if the user refreshes the page. Though, I'd like to echo Tim and say that if I assumed incorrectly, you should post your code.