How to implement movement in a chess game ? - c#

I am learning to make a small variant of chess game using windows forms C#, the game includes only the pawns of both sides, i have drew the board and organized the pieces on there places, but i honestly do not know how to start implementing the moves by clicking the mouse on the piece and then the location where i want to move it.
as references the black pawn is named piece, and white pawn is named pieceW
here is my code for the board
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AIchess
{
public partial class Form1 : Form
{
static System.Drawing.Bitmap piece = AIchess.Properties.Resources.piece;
ChessPiece Piece = new ChessPiece(piece, ChessColor.Black);
static System.Drawing.Bitmap pieceW = AIchess.Properties.Resources.pieceW;
ChessPiece PieceW = new ChessPiece(pieceW, ChessColor.White);
Square[,] square = new Square[8, 8];
public Form1()
{
InitializeComponent();
int i, j;
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
this.square[i, j] = new Square();
this.square[i, j].BackColor = System.Drawing.SystemColors.ActiveCaption;
this.square[i, j].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.square[i, j].Location = new System.Drawing.Point(57 + i * 60, 109 + j * 60);
this.square[i, j].Name = i.ToString()+j.ToString();
this.square[i, j].Size = new System.Drawing.Size(60, 60);
this.square[i, j].TabIndex = 2;
this.square[i, j].TabStop = false;
this.Controls.Add(this.square[i, j]);
if (j == 1)
{
this.square[i, j].Image = piece;
this.square[i, j].AllocatedBy = "black";
}
if (j == 6)
{
this.square[i, j].Image = pieceW;
this.square[i, j].AllocatedBy = "white";
}
if (((i+j) % 2) ==0)
this.square[i, j].BackColor = Color.RoyalBlue;
else
this.square[i, j].BackColor = Color.LightBlue;
}
}
}
}
public enum ChessColor
{
White,
Black,
};
class ChessPiece
{
private Image DisplayedImage;
private ChessColor DisplayedColor;
private Point CurrentSquare;
public ChessPiece(Image image, ChessColor color)
{
DisplayedImage = image;
DisplayedColor = color;
}
}
class Square:PictureBox
{
private bool color;
public string AllocatedBy;
}
}

Here's a really simple implementation, I hope you won't mind that I did it from scratch.
Obviously it's very simple, there's no drag and drop and no animation but it fulfills your requirement.
I'll go through each part and explain them
InitializeGame
There you do set your images dimensions (they should be identical obviously)
You add in the dictionary the relationship between piece type/color and your bitmap
Note : the grid will be scaled so you can throw any size of bitmap you like
CreateBoard, DrawGame, DrawPieces
Nothing exceptional in there, note that for keeping things simple I do that every time a user clicks but it shouldn't be much of an issue, it's not Crysis after all :D
PickOrDropPiece
This is the logic where picking/dropping happens, it's really trivial and I'll let you take a look by yourself.
Differences between your code
I've created a Board type which holds the pieces and that you can easily update.
Note : do not remove the equality members in Piece they are here to help the dictionary.
Make sure to use 32-bit bitmaps with transparent borders
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox1.MouseDown += pictureBox1_MouseDown;
}
#region Properties
private Board Board { get; set; }
private Piece CurrentPiece { get; set; }
private Dictionary<Piece, Bitmap> PieceBitmaps { get; set; }
private int TileWidth { get; set; }
private int TileHeight { get; set; }
#endregion
#region Events
private void Form1_Load(object sender, EventArgs e)
{
InitializeGame();
DrawGame();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
PickOrDropPiece(e);
DrawGame();
}
#endregion
#region Methods
private void InitializeGame()
{
TileWidth = 64;
TileHeight = 64;
Board = new Board();
PieceBitmaps = new Dictionary<Piece, Bitmap>();
PieceBitmaps.Add(new Piece(PieceType.Pawn, PieceColor.Black), new Bitmap("pawnblack.png"));
PieceBitmaps.Add(new Piece(PieceType.Pawn, PieceColor.White), new Bitmap("pawnwhite.png"));
}
private void DrawGame()
{
var tileSize = new Size(TileWidth, TileHeight);
Bitmap bitmap = CreateBoard(tileSize);
DrawPieces(bitmap);
pictureBox1.Image = bitmap;
}
private Bitmap CreateBoard(Size tileSize)
{
int tileWidth = tileSize.Width;
int tileHeight = tileSize.Height;
var bitmap = new Bitmap(tileWidth*8, tileHeight*8);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Brush brush = (x%2 == 0 && y%2 == 0) || (x%2 != 0 && y%2 != 0) ? Brushes.Black : Brushes.White;
graphics.FillRectangle(brush, new Rectangle(x*tileWidth, y*tileHeight, tileWidth, tileHeight));
}
}
}
return bitmap;
}
private void DrawPieces(Bitmap bitmap)
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Board board = Board;
for (int x = 0; x < 8; x++)
{
for (int y = 0; y < 8; y++)
{
Piece piece = board.GetPiece(x, y);
if (piece != null)
{
Bitmap bitmap1 = PieceBitmaps[piece];
graphics.DrawImageUnscaled(bitmap1, new Point(x*TileWidth, y*TileHeight));
}
}
}
}
}
private void PickOrDropPiece(MouseEventArgs e)
{
Point location = e.Location;
int x = location.X/TileWidth;
int y = location.Y/TileHeight;
bool pickOrDrop = CurrentPiece == null;
if (pickOrDrop)
{
// Pick a piece
Piece piece = Board.GetPiece(x, y);
Board.SetPiece(x, y, null);
if (piece != null)
{
label1.Text = string.Format("You picked a {0} {1} at location {2},{3}", piece.Color, piece.Type, x,
y);
}
else
{
label1.Text = "Nothing there !";
}
CurrentPiece = piece;
}
else
{
// Drop picked piece
Board.SetPiece(x, y, CurrentPiece);
label1.Text = string.Format("You dropped a {0} {1} at location {2},{3}", CurrentPiece.Color,
CurrentPiece.Type, x,
y);
CurrentPiece = null;
}
}
#endregion
}
public class Board
{
private readonly Piece[] _pieces;
public Board()
{
_pieces = new Piece[8*8];
PopulatePieces();
}
public Piece GetPiece(int x, int y)
{
int i = y*8 + x;
return _pieces[i];
}
public void SetPiece(int x, int y, Piece piece)
{
int i = y*8 + x;
_pieces[i] = piece;
}
private void PopulatePieces()
{
for (int i = 0; i < 8; i++)
{
SetPiece(i, 1, new Piece(PieceType.Pawn, PieceColor.Black));
SetPiece(i, 7, new Piece(PieceType.Pawn, PieceColor.White));
}
}
}
public class Piece
{
private readonly PieceColor _color;
private readonly PieceType _type;
public Piece(PieceType type, PieceColor color)
{
_type = type;
_color = color;
}
public PieceType Type
{
get { return _type; }
}
public PieceColor Color
{
get { return _color; }
}
protected bool Equals(Piece other)
{
return _color == other._color && _type == other._type;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Piece) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((int) _color*397) ^ (int) _type;
}
}
public static bool operator ==(Piece left, Piece right)
{
return Equals(left, right);
}
public static bool operator !=(Piece left, Piece right)
{
return !Equals(left, right);
}
}
public enum PieceType
{
Pawn
}
public enum PieceColor
{
Black,
White
}
}

Related

Unable to get objects to collide

For the life of me, I cannot figure out what I am doing wrong. I have managed to make a player and make it shoot. I've also managed to make balls spawn in at random locations/speeds in the picture box.
I can't get any Collision to work. I am trying to keep all balls in the picture box and bounce back and also bounce off each other, and then destroy them when shot.
I have been trying to use Ball.Bounds.IntersectsWith(pictureBox2.Bounds), but it seems that Ball.bounds is wrong.
I have a vague idea why it is wrong but not definitive. My property bounds in box.cs is either wrong or I don't know how to make that relate to positioning all my balls.
A little nudge in the right direction would be appreciated as I have been stuck on this issue for a while now.
ball.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace shootyarcher
{
class Ball : Box
{
public string bounds { get; set; }
static private Random generator = new Random();
private int countdown;
public Ball ()
{
pic = Properties.Resources.Balloon;
x = generator.Next(60, 1920);
y = generator.Next(100, 1000);
xspeed = generator.Next(-10, 4);
yspeed = generator.Next(-10, 4);
countdown = generator.Next(100, 200);
}
public new void Move()
{
countdown--;
if (countdown == 0)
{
xspeed = generator.Next(-4, 4);
yspeed = generator.Next(-4, 4);
countdown = generator.Next(20, 40);
}
x = x + xspeed;
y = y + yspeed;
}
}
}
box.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing; //pictures
namespace shootyarcher
{
class Box
{
public float x;
public float y;
public float w;
public float h;
public float xspeed;
public float yspeed;
public Image pic;
public Box() // constructor
{
x = 0;
y = 0;
xspeed = 0;
yspeed = 0;
}
public void Move()
{
x = x + xspeed;
y = y + yspeed;
}
public void Draw(Graphics g)
{
g.DrawImage (pic, x, y);
}
public float Width()
{
return pic.Width;
}
public float Height()
{
return pic.Height;
}
public float Left()
{
return x;
}
public float Right()
{
return x + Width();
}
public float Top()
{
return y;
}
public float Bottom()
{
return y + Height();
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace shootyarcher
{
public partial class Form1 : Form
{
Archer player;
List<Arrow> Shiv;
List<Ball> Kill;
public Form1()
{
InitializeComponent();
Cursor.Hide();
this.FormBorderStyle = FormBorderStyle.None;
this.TopMost = true;
this.Bounds = Screen.PrimaryScreen.Bounds;
player = new Archer(0, 0);
Shiv = new List<Arrow>();
Kill = new List<Ball>();
for (int i = 0; i < 400; i++)
{
Ball temp = new Ball();
Kill.Add(temp);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
player.Move();
foreach (Arrow t in Shiv)
{
t.Move();
}
foreach (Ball m in Kill)
{
m.Move();
}
pictureBox1.Invalidate();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
player.moveup = true;
}
if (e.KeyCode == Keys.S)
{
player.movedown = true;
}
if (e.KeyCode == Keys.Space)
{
Arrow temp = new Arrow(player.x, player.y);
Shiv.Add(temp);
}
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
player.moveup = false;
}
if (e.KeyCode == Keys.S)
{
player.movedown = false;
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
player.Draw(e.Graphics);
foreach (Arrow t in Shiv)
{
t.Draw(e.Graphics);
}
foreach (Ball m in Kill)
{
m.Draw(e.Graphics);
}
}
}
}

C# unable to move character in ASCII Console game

I have a C# project for school. I am unable to move my character in this ASCII console game. It has to be OO. After I run the code I get this:
After I press left or right I get
Can someone help me on this? Any help is appreciated.
program.cs:
class Program
{
static void Main(string[] args)
{
SuperConsole.Init(50, 44);
// create the game
Game game = new Game(30, 30);
//create objects
Entity spaceship = new Entity(1, 15, '#', SuperConsoleColor.Cyan);
// start the game loop
RunGameLoop(game);
}
protected static void RunGameLoop(Game game)
{
SuperConsole.BackgroundColor = SuperConsoleColor.DarkBlue;
SuperConsole.ForegroundColor = SuperConsoleColor.Gray;
int refreshRate = 20;
SuperConsole.CursorVisible = false;
SuperConsole.BackgroundColor = SuperConsoleColor.DarkBlue;
SuperConsole.ForegroundColor = SuperConsoleColor.Gray;
SuperConsole.Clear();
Reset(game);
game.Draw(0.0f);
SuperConsole.Flush();
/*
SuperConsole.SetCursorPosition(0, 0);*/
while (true)
{
while (SuperConsole.KeyAvailable)
{
ConsoleKeyInfo key = SuperConsole.ReadKey(true);
game.OnInput(key.Key);
}
System.Threading.Thread.Sleep(1000 / refreshRate);
Reset(game);
game.Draw(1.0f / (float)refreshRate);
SuperConsole.Flush();
}
}
protected static void Reset(Game game)
{
SuperConsole.BackgroundColor = SuperConsoleColor.Black;
SuperConsole.ForegroundColor = SuperConsoleColor.Black;
SuperConsole.SetCursorPosition(0, 0);
for (int y = 0; y < game.GetHeight(); ++y)
{
for (int x = 0; x < game.GetWidth(); ++x)
{
SuperConsole.Write(" ");
}
SuperConsole.WriteLine();
}
SuperConsole.SetCursorPosition(0, 0);
}
}
}
game.cs:
class Game : Entity
{
protected int width, height;
Entity spaceship = new Entity(1, 15, '#', SuperConsoleColor.Cyan);
public Game(int newWidth, int newHeight)
{
// set the size
width = newWidth;
height = newHeight;
// set the window
Console.WindowWidth = width+1;
Console.WindowHeight = height+1;
}
public int GetWidth()
{
return width;
}
public int GetHeight()
{
return height;
}
public void Draw(float dt)
{
SuperConsole.SetCursorPosition(spaceship.GetX(), spaceship.GetY());
SuperConsole.ForegroundColor = spaceship.GetColour();
SuperConsole.Write(spaceship.GetChar());
}
public void OnInput(ConsoleKey key)
{
int redo = 0;
ConsoleKey pressedKey = key;
do
{
Console.Clear();
switch (pressedKey)
{
case ConsoleKey.LeftArrow:
SuperConsole.SetCursorPosition(spaceship.GetX() - 1, spaceship.GetY());
break;
case ConsoleKey.UpArrow:
break;
case ConsoleKey.RightArrow:
SuperConsole.SetCursorPosition(spaceship.GetX()+1, spaceship.GetY());
break;
case ConsoleKey.DownArrow:
break;
}
} while (redo == 0);
}
}
}
entity.cs:
class Entity
{
protected int xPos;
protected int yPos;
protected char character;
protected SuperConsoleColor colour;
public Entity()
{
}
public Entity(int xPosNew, int yPosNew, char newCharacter, SuperConsoleColor newColour)
{
//define position
xPos = xPosNew;
yPos = yPosNew;
//define character
character = newCharacter;
//define colour
colour = newColour;
}
public char GetChar()
{
return character;
}
public int GetX()
{
return xPos;
}
public int GetY()
{
return yPos;
}
public SuperConsoleColor GetColour()
{
return colour;
}
}
}
I see two issues:
Within RunGameLoop(Game game) you should replace while (SuperConsole.KeyAvailable) with if (SuperConsole.KeyAvailable).
Within Game.OnInput(ConsoleKey) you change the cursor position instead of the spaceship position
Also try using breakpoints to Check if the code reaches Game.Draw() and check if the spaceship position and the cursor position are correct.
Also you should get a bit more into C#.
Instead of
public char GetChar()
{
return character;
}
private character;
.Net allows you to use Properties:
public char Character
{
get; private set;
}
or
public char Character
{
get { return character; }
}
private character = '#';
Hope this helps.
Apart from that: No offense, but this question isn't really what Stackoverflow is for. In future, please be more patient and try to googling debugging tips instead of letting Stackoverflow do the 'dirty work' for you.

xamarin ViewPager Android

I was trying to create a Sliding-Tab-Layout. I followed this tutorial Sliding Tab Layout
and it was great, but I wanted to Load Specific Layout in each TabView
I also want to make each one loaded, when I select it or scroll to it just like facebook application.
The reason is not to take so much time to load for each View in ViewPager
and there is the classes:
SlidingTabStrip
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Util;
namespace SlidingTabLayoutTutorial
{
public class SlidingTabStrip : LinearLayout
{
//Copy and paste from here................................................................
private const int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
private const byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0X26;
private const int SELECTED_INDICATOR_THICKNESS_DIPS = 3;
private int[] INDICATOR_COLORS = { 0xffffff };
private int[] DIVIDER_COLORS = { 0xffffff };
private const int DEFAULT_DIVIDER_THICKNESS_DIPS = 1;
private const float DEFAULT_DIVIDER_HEIGHT = 0.5f;
//Bottom border
private int mBottomBorderThickness;
private Paint mBottomBorderPaint;
private int mDefaultBottomBorderColor;
//Indicator
private int mSelectedIndicatorThickness;
private Paint mSelectedIndicatorPaint;
//Divider
private Paint mDividerPaint;
private float mDividerHeight;
//Selected position and offset
private int mSelectedPosition;
private float mSelectionOffset;
//Tab colorizer
private SlidingTabScrollView.TabColorizer mCustomTabColorizer;
private SimpleTabColorizer mDefaultTabColorizer;
//Stop copy and paste here........................................................................
//Constructors
public SlidingTabStrip (Context context) : this(context, null)
{ }
public SlidingTabStrip (Context context, IAttributeSet attrs) : base(context, attrs)
{
SetWillNotDraw(false);
float density = Resources.DisplayMetrics.Density;
TypedValue outValue = new TypedValue();
context.Theme.ResolveAttribute(Android.Resource.Attribute.ColorForeground, outValue, true);
int themeForeGround = outValue.Data;
mDefaultBottomBorderColor = SetColorAlpha(themeForeGround, DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.IndicatorColors = INDICATOR_COLORS;
mDefaultTabColorizer.DividerColors = DIVIDER_COLORS;
mBottomBorderThickness = (int)(DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.Color = GetColorFromInteger(0x1B729E); //Gray
mSelectedIndicatorThickness = (int)(SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
mDividerHeight = DEFAULT_DIVIDER_HEIGHT;
mDividerPaint = new Paint();
mDividerPaint.StrokeWidth = (int)(DEFAULT_DIVIDER_THICKNESS_DIPS * density);
}
public SlidingTabScrollView.TabColorizer CustomTabColorizer
{
set
{
mCustomTabColorizer = value;
this.Invalidate();
}
}
public int [] SelectedIndicatorColors
{
set
{
mCustomTabColorizer = null;
mDefaultTabColorizer.IndicatorColors = value;
this.Invalidate();
}
}
public int [] DividerColors
{
set
{
mDefaultTabColorizer = null;
mDefaultTabColorizer.DividerColors = value;
this.Invalidate();
}
}
private Color GetColorFromInteger(int color)
{
return Color.Rgb(Color.GetRedComponent(color), Color.GetGreenComponent(color), Color.GetBlueComponent(color));
}
private int SetColorAlpha(int color, byte alpha)
{
return Color.Argb(alpha, Color.GetRedComponent(color), Color.GetGreenComponent(color), Color.GetBlueComponent(color));
}
public void OnViewPagerPageChanged(int position, float positionOffset)
{
mSelectedPosition = position;
mSelectionOffset = positionOffset;
this.Invalidate();
}
protected override void OnDraw(Canvas canvas)
{
int height = Height;
int tabCount = ChildCount;
int dividerHeightPx = (int)(Math.Min(Math.Max(0f, mDividerHeight), 1f) * height);
SlidingTabScrollView.TabColorizer tabColorizer = mCustomTabColorizer != null ? mCustomTabColorizer : mDefaultTabColorizer;
//Thick colored underline below the current selection
if (tabCount > 0)
{
View selectedTitle = GetChildAt(mSelectedPosition);
int left = selectedTitle.Left;
int right = selectedTitle.Right;
int color = tabColorizer.GetIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (tabCount - 1))
{
int nextColor = tabColorizer.GetIndicatorColor(mSelectedPosition + 1);
if (color != nextColor)
{
color = blendColor(nextColor, color, mSelectionOffset);
}
View nextTitle = GetChildAt(mSelectedPosition + 1);
left = (int)(mSelectionOffset * nextTitle.Left + (1.0f - mSelectionOffset) * left);
right = (int)(mSelectionOffset * nextTitle.Right + (1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.Color = GetColorFromInteger(color);
canvas.DrawRect(left, height - mSelectedIndicatorThickness, right, height, mSelectedIndicatorPaint);
//Creat vertical dividers between tabs
int separatorTop = (height - dividerHeightPx) / 2;
for (int i = 0; i < ChildCount -1; i++)
{
View child = GetChildAt(i);
mDividerPaint.Color = GetColorFromInteger(tabColorizer.GetDividerColor(i));
canvas.DrawLine(child.Right, separatorTop, child.Right, separatorTop + dividerHeightPx, mDividerPaint);
}
canvas.DrawRect(0, height - mBottomBorderThickness, Width, height, mBottomBorderPaint);
}
}
private int blendColor(int color1, int color2, float ratio)
{
float inverseRatio = 1f - ratio;
float r = (Color.GetRedComponent(color1) * ratio) + (Color.GetRedComponent(color2) * inverseRatio);
float g = (Color.GetGreenComponent(color1) * ratio) + (Color.GetGreenComponent(color2) * inverseRatio);
float b = (Color.GetBlueComponent(color1) * ratio) + (Color.GetBlueComponent(color2) * inverseRatio);
return Color.Rgb((int)r, (int)g, (int)b);
}
private class SimpleTabColorizer : SlidingTabScrollView.TabColorizer
{
private int[] mIndicatorColors;
private int[] mDividerColors;
public int GetIndicatorColor(int position)
{
return mIndicatorColors[position % mIndicatorColors.Length];
}
public int GetDividerColor (int position)
{
return mDividerColors[position % mDividerColors.Length];
}
public int[] IndicatorColors
{
set { mIndicatorColors = value; }
}
public int[] DividerColors
{
set { mDividerColors = value; }
}
}
}
}
SlidingTabScrollView
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.View;
using Android.Util;
using Android.Graphics;
namespace SlidingTabLayoutTutorial
{
public class SlidingTabScrollView : HorizontalScrollView
{
private const int TITLE_OFFSET_DIPS = 15;
private const int TAB_VIEW_PADDING_DIPS = 15;
private const int TAB_VIEW_TEXT_SIZE_SP = 20;
private int mTitleOffset;
//private int mTabViewLayoutID;
//private int mTabViewTextViewID;
private ViewPager mViewPager;
private ViewPager.IOnPageChangeListener mViewPagerPageChangeListener;
private static SlidingTabStrip mTabStrip;
private int mScrollState;
public interface TabColorizer
{
int GetIndicatorColor(int position);
int GetDividerColor(int position);
}
public SlidingTabScrollView(Context context) : this(context, null) { }
public SlidingTabScrollView(Context context, IAttributeSet attrs) : this(context, attrs, 0) { }
public SlidingTabScrollView (Context context, IAttributeSet attrs, int defaultStyle) : base(context, attrs, defaultStyle)
{
//Disable the scroll bar
HorizontalScrollBarEnabled = false;
//Make sure the tab strips fill the view
FillViewport = true;
this.SetBackgroundColor(Android.Graphics.Color.ParseColor("#0078FF")); //Gray color
mTitleOffset = (int)(TITLE_OFFSET_DIPS * Resources.DisplayMetrics.Density);
mTabStrip = new SlidingTabStrip(context);
mTabStrip.WeightSum = 3;
this.AddView(mTabStrip, LayoutParams.MatchParent, LayoutParams.MatchParent);
}
public TabColorizer CustomTabColorizer
{
set { mTabStrip.CustomTabColorizer = value; }
}
public int [] SelectedIndicatorColor
{
set { mTabStrip.SelectedIndicatorColors = value; }
}
public int [] DividerColors
{
set { mTabStrip.DividerColors = value; }
}
public ViewPager.IOnPageChangeListener OnPageListener
{
set { mViewPagerPageChangeListener = value; }
}
public ViewPager ViewPager
{
set
{
mTabStrip.RemoveAllViews();
mViewPager = value;
if (value != null)
{
value.PageSelected += value_PageSelected;
value.PageScrollStateChanged += value_PageScrollStateChanged;
value.PageScrolled += value_PageScrolled;
PopulateTabStrip();
}
}
}
void value_PageScrolled(object sender, ViewPager.PageScrolledEventArgs e)
{
int tabCount = mTabStrip.ChildCount;
if ((tabCount == 0) || (e.Position < 0) || (e.Position >= tabCount))
{
//if any of these conditions apply, return, no need to scroll
return;
}
mTabStrip.OnViewPagerPageChanged(e.Position, e.PositionOffset);
View selectedTitle = mTabStrip.GetChildAt(e.Position);
int extraOffset = (selectedTitle != null ? (int)(e.Position * selectedTitle.Width) : 0);
ScrollToTab(e.Position, extraOffset);
if (mViewPagerPageChangeListener != null)
{
mViewPagerPageChangeListener.OnPageScrolled(e.Position, e.PositionOffset, e.PositionOffsetPixels);
}
}
void value_PageScrollStateChanged(object sender, ViewPager.PageScrollStateChangedEventArgs e)
{
mScrollState = e.State;
if (mViewPagerPageChangeListener != null)
{
mViewPagerPageChangeListener.OnPageScrollStateChanged(e.State);
}
}
void value_PageSelected(object sender, ViewPager.PageSelectedEventArgs e)
{
if (mScrollState == ViewPager.ScrollStateIdle)
{
mTabStrip.OnViewPagerPageChanged(e.Position, 0f);
ScrollToTab(e.Position, 0);
}
if (mViewPagerPageChangeListener != null)
{
mViewPagerPageChangeListener.OnPageSelected(e.Position);
}
}
private void PopulateTabStrip()
{
PagerAdapter adapter = mViewPager.Adapter;
for (int i = 0; i < adapter.Count; i++)
{
TextView tabView = CreateDefaultTabView(Context);
tabView.Text = ((SlidingTabsFragment.SamplePagerAdapter)adapter).GetHeaderTitle(i);
tabView.SetTextColor(Android.Graphics.Color.White);
tabView.Tag = i;
tabView.Click += tabView_Click;
mTabStrip.AddView(tabView);
}
}
void tabView_Click(object sender, EventArgs e)
{
TextView clickTab = (TextView)sender;
int pageToScrollTo = (int)clickTab.Tag;
mViewPager.CurrentItem = pageToScrollTo;
}
private TextView CreateDefaultTabView(Android.Content.Context context )
{
TextView textView = new TextView(context);
textView.Gravity = GravityFlags.Center;
textView.SetTextSize(ComplexUnitType.Sp, TAB_VIEW_TEXT_SIZE_SP);
textView.Typeface = Android.Graphics.Typeface.Default;
textView.LayoutParameters = new LinearLayout.LayoutParams(0, LayoutParams.MatchParent, 1);
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Honeycomb)
{
TypedValue outValue = new TypedValue();
Context.Theme.ResolveAttribute(Android.Resource.Attribute.SelectableItemBackground, outValue, false);
textView.SetBackgroundResource(outValue.ResourceId);
}
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.IceCreamSandwich)
{
textView.SetAllCaps(true);
}
int padding = (int)(TAB_VIEW_PADDING_DIPS * Resources.DisplayMetrics.Density);
textView.SetPadding(padding, padding, padding, padding);
return textView;
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
if (mViewPager != null)
{
ScrollToTab(mViewPager.CurrentItem, 0);
}
}
private void ScrollToTab(int tabIndex, int extraOffset)
{
int tabCount = mTabStrip.ChildCount;
if (tabCount == 0 || tabIndex < 0 || tabIndex >= tabCount)
{
//No need to go further, dont scroll
return;
}
View selectedChild = mTabStrip.GetChildAt(tabIndex);
if (selectedChild != null)
{
int scrollAmountX = selectedChild.Left + extraOffset;
if (tabIndex >0 || extraOffset > 0)
{
scrollAmountX -= mTitleOffset;
}
this.ScrollTo(scrollAmountX, 0);
}
}
}
}
SlidingTabsFragment
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Support.V4.View;
namespace SlidingTabLayoutTutorial
{
public class SlidingTabsFragment : Fragment
{
private SlidingTabScrollView mSlidingTabScrollView;
private ViewPager mViewPager;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.Inflate(Resource.Layout.fragment_sample, container, false);
}
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
mSlidingTabScrollView = view.FindViewById<SlidingTabScrollView>(Resource.Id.sliding_tabs);
mViewPager = view.FindViewById<ViewPager>(Resource.Id.viewpager);
mViewPager.Adapter = new SamplePagerAdapter();
mSlidingTabScrollView.ViewPager = mViewPager;
}
public class SamplePagerAdapter : PagerAdapter
{
List<string> items = new List<string>();
public SamplePagerAdapter() : base()
{
items.Add("Home");
items.Add("Sell");
items.Add("Rent");
}
public override int Count
{
get { return items.Count; }
}
public override bool IsViewFromObject(View view, Java.Lang.Object obj)
{
return view == obj;
}
public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)
{
View view = LayoutInflater.From(container.Context).Inflate(Resource.Layout.pager_item, container, false);
container.AddView(view);
TextView txtTitle = view.FindViewById<TextView>(Resource.Id.item_title);
int pos = position + 1;
txtTitle.Text = pos.ToString();
return view;
}
public string GetHeaderTitle (int position)
{
return items[position];
}
public override void DestroyItem(ViewGroup container, int position, Java.Lang.Object obj)
{
container.RemoveView((View)obj);
}
}
}
}
MainActivity
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Support.V4.View;
namespace SlidingTabLayoutTutorial
{
[Activity(Label = "Sliding Tab Layout", MainLauncher = true, Icon = "#drawable/xs")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
FragmentTransaction transaction = FragmentManager.BeginTransaction();
SlidingTabsFragment fragment = new SlidingTabsFragment();
transaction.Replace(Resource.Id.sample_content_fragment, fragment);
transaction.Commit();
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.actionbar_main, menu);
return base.OnCreateOptionsMenu(menu);
}
}
}
I think you need to add in your code something like this : (in OnCreateView() )
position => comes from the adapter..
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
switch (position)
{
case 0:
view = (ViewGroup)inflater.Inflate(Resource.Layout.Page1, container, false);
break;
case 1:
view = (ViewGroup)inflater.Inflate(Resource.Layout.Page2, container, false);
btn_forexample = view.FindViewById<Button>(Resource.Id.btn_forexample);
break;
case 2:
view = (ViewGroup)inflater.Inflate(Resource.Layout.Page3, container, false);
break;
default:
view = (ViewGroup)inflater.Inflate(Resource.Layout.DefaultPage, container, false);
break;
}
return view;
}
Hope it helps ;)

Change Splitter Highlighting/Resize Line

I noticed when I resize an element in Visual Studio the Splitter Line is painted in a solid transparent black like this:
However in my own Winforms application I get this resize line:
I am wondering how I can change the painting of this resize line?
If you take a look at Splitter source code, you will see drawing of the highlight is performed in the DrawSplitHelper private method.
Since splitter methods are tightly deppending on private members of the control, overriding members or handling events of the control which use this method doesn't provides such transparent highlight simply. Also if you decide to darw a solid highlight, you can not have a filcker-free drawing because of the halftone highlight which the control draws in private methods.
The idea of showing a transparent highlight is based on showing a top-most semi-transparent window which doesn't activate on showing. Also you can use PatBlt method to draw a reversible rectangle using a brush.
As an option I started by Splitter.cs and changed it to draw desired transparent highlight as you see in image below:
Code
As an option I started by Splitter.cs and changed it to draw desired transparent highlight. I used a Form to show transparent highlight. I showed the form without activating, as top-most and with a suitable opacity.
Probably you can create a splitter using less code, but I preferred to use source code of Splitter instead of writing my own splitter. Thanks to Microsoft for sharing source code.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Drawing.Drawing2D;
using System.Reflection;
[ComVisible(true)]
[DefaultEvent("SplitterMoved")]
[DefaultProperty("Dock")]
[Designer(typeof(MySplitterDesigner))]
public class MySplitter : Control
{
private Point anchor = Point.Empty;
private System.Windows.Forms.BorderStyle borderStyle;
private const int defaultWidth = 3;
private const int DRAW_END = 3;
private const int DRAW_MOVE = 2;
private const int DRAW_START = 1;
private static readonly object EVENT_MOVED = new object();
private static readonly object EVENT_MOVING = new object();
private int initTargetSize;
private int lastDrawSplit = -1;
private int maxSize;
private int minExtra = 25;
private int minSize = 25;
private int splitSize = -1;
private Control splitTarget;
private SplitterMessageFilter splitterMessageFilter;
private int splitterThickness = 3;
[Category("Behavior")]
[Description("Occurs when the splitter is done being moved.")]
public event SplitterEventHandler SplitterMoved
{
add
{
base.Events.AddHandler(EVENT_MOVED, value);
}
remove
{
base.Events.RemoveHandler(EVENT_MOVED, value);
}
}
[Category("Behavior")]
[Description("Occurs when the splitter is being moved.")]
public event SplitterEventHandler SplitterMoving
{
add
{
base.Events.AddHandler(EVENT_MOVING, value);
}
remove
{
base.Events.RemoveHandler(EVENT_MOVING, value);
}
}
HighLight highlight;
public MySplitter()
{
base.SetStyle(ControlStyles.Selectable, false);
this.TabStop = false;
this.minSize = 0x19;
this.minExtra = 0x19;
this.Dock = DockStyle.Left;
highlight = new HighLight();
}
private void ApplySplitPosition()
{
this.SplitPosition = this.splitSize;
}
private SplitData CalcSplitBounds()
{
SplitData data = new SplitData();
Control control = this.FindTarget();
data.target = control;
if (control != null)
{
switch (control.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
this.initTargetSize = control.Bounds.Height;
break;
case DockStyle.Left:
case DockStyle.Right:
this.initTargetSize = control.Bounds.Width;
break;
}
Control parentInternal = this.Parent;
Control.ControlCollection controls = parentInternal.Controls;
int count = controls.Count;
int num2 = 0;
int num3 = 0;
for (int i = 0; i < count; i++)
{
Control control3 = controls[i];
if (control3 != control)
{
switch (control3.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
num3 += control3.Height;
break;
case DockStyle.Left:
case DockStyle.Right:
num2 += control3.Width;
break;
}
}
}
Size clientSize = parentInternal.ClientSize;
if (this.Horizontal)
{
this.maxSize = (clientSize.Width - num2) - this.minExtra;
}
else
{
this.maxSize = (clientSize.Height - num3) - this.minExtra;
}
data.dockWidth = num2;
data.dockHeight = num3;
}
return data;
}
private Rectangle CalcSplitLine(int splitSize, int minWeight)
{
Rectangle bounds = base.Bounds;
Rectangle rectangle2 = this.splitTarget.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
if (bounds.Height < minWeight)
{
bounds.Height = minWeight;
}
bounds.Y = rectangle2.Y + splitSize;
return bounds;
case DockStyle.Bottom:
if (bounds.Height < minWeight)
{
bounds.Height = minWeight;
}
bounds.Y = ((rectangle2.Y + rectangle2.Height) - splitSize) - bounds.Height;
return bounds;
case DockStyle.Left:
if (bounds.Width < minWeight)
{
bounds.Width = minWeight;
}
bounds.X = rectangle2.X + splitSize;
return bounds;
case DockStyle.Right:
if (bounds.Width < minWeight)
{
bounds.Width = minWeight;
}
bounds.X = ((rectangle2.X + rectangle2.Width) - splitSize) - bounds.Width;
return bounds;
}
return bounds;
}
private int CalcSplitSize()
{
Control control = this.FindTarget();
if (control != null)
{
Rectangle bounds = control.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
return bounds.Height;
case DockStyle.Left:
case DockStyle.Right:
return bounds.Width;
}
}
return -1;
}
private void DrawSplitBar(int mode)
{
if ((mode != 1) && (this.lastDrawSplit != -1))
{
this.DrawSplitHelper(this.lastDrawSplit);
this.lastDrawSplit = -1;
}
else if ((mode != 1) && (this.lastDrawSplit == -1))
{
return;
}
if (mode != 3)
{
this.DrawSplitHelper(this.splitSize);
this.lastDrawSplit = this.splitSize;
}
else
{
if (this.lastDrawSplit != -1)
{
this.DrawSplitHelper(this.lastDrawSplit);
}
this.lastDrawSplit = -1;
highlight.Hide();
}
Console.WriteLine(mode);
}
private void DrawSplitHelper(int splitSize)
{
if (this.splitTarget != null)
{
Rectangle rectangle = this.CalcSplitLine(splitSize, 3);
var r = this.Parent.RectangleToScreen(rectangle);
if (!highlight.Visible)
highlight.ShowInactiveTopmost();
highlight.Location = r.Location;
highlight.Size = r.Size;
}
}
private Control FindTarget()
{
Control parentInternal = this.Parent;
if (parentInternal != null)
{
Control.ControlCollection controls = parentInternal.Controls;
int count = controls.Count;
DockStyle dock = this.Dock;
for (int i = 0; i < count; i++)
{
Control control2 = controls[i];
if (control2 != this)
{
switch (dock)
{
case DockStyle.Top:
if (control2.Bottom != base.Top)
{
break;
}
return control2;
case DockStyle.Bottom:
if (control2.Top != base.Bottom)
{
break;
}
return control2;
case DockStyle.Left:
if (control2.Right != base.Left)
{
break;
}
return control2;
case DockStyle.Right:
if (control2.Left != base.Right)
{
break;
}
return control2;
}
}
}
}
return null;
}
private int GetSplitSize(int x, int y)
{
int num;
if (this.Horizontal)
num = x - this.anchor.X;
else
num = y - this.anchor.Y;
int num2 = 0;
switch (this.Dock)
{
case DockStyle.Top:
num2 = this.splitTarget.Height + num;
break;
case DockStyle.Bottom:
num2 = this.splitTarget.Height - num;
break;
case DockStyle.Left:
num2 = this.splitTarget.Width + num;
break;
case DockStyle.Right:
num2 = this.splitTarget.Width - num;
break;
}
return Math.Max(Math.Min(num2, this.maxSize), this.minSize);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if ((this.splitTarget != null) && (e.KeyCode == Keys.Escape))
this.SplitEnd(false);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if ((e.Button == MouseButtons.Left) && (e.Clicks == 1))
this.SplitBegin(e.X, e.Y);
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (this.splitTarget != null)
{
int x = e.X + base.Left;
int y = e.Y + base.Top;
Rectangle rectangle = this.CalcSplitLine(this.GetSplitSize(e.X, e.Y), 0);
int splitX = rectangle.X;
int splitY = rectangle.Y;
this.OnSplitterMoving(new SplitterEventArgs(x, y, splitX, splitY));
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (this.splitTarget != null)
{
Rectangle rectangle = this.CalcSplitLine(this.GetSplitSize(e.X, e.Y), 0);
this.SplitEnd(true);
}
}
protected virtual void OnSplitterMoved(SplitterEventArgs sevent)
{
SplitterEventHandler handler = (SplitterEventHandler)base.Events[EVENT_MOVED];
if (handler != null)
handler(this, sevent);
if (this.splitTarget != null)
this.SplitMove(sevent.SplitX, sevent.SplitY);
}
protected virtual void OnSplitterMoving(SplitterEventArgs sevent)
{
SplitterEventHandler handler = (SplitterEventHandler)base.Events[EVENT_MOVING];
if (handler != null)
handler(this, sevent);
if (this.splitTarget != null)
this.SplitMove(sevent.SplitX, sevent.SplitY);
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
if (this.Horizontal)
{
if (width < 1)
width = 3;
this.splitterThickness = width;
}
else
{
if (height < 1)
height = 3;
this.splitterThickness = height;
}
base.SetBoundsCore(x, y, width, height, specified);
}
private void SplitBegin(int x, int y)
{
SplitData data = this.CalcSplitBounds();
if ((data.target != null) && (this.minSize < this.maxSize))
{
this.anchor = new Point(x, y);
this.splitTarget = data.target;
this.splitSize = this.GetSplitSize(x, y);
try
{
if (this.splitterMessageFilter != null)
this.splitterMessageFilter = new SplitterMessageFilter(this);
Application.AddMessageFilter(this.splitterMessageFilter);
}
finally { }
this.Capture = true;
this.DrawSplitBar(1);
}
}
private void SplitEnd(bool accept)
{
this.DrawSplitBar(3);
this.splitTarget = null;
this.Capture = false;
if (this.splitterMessageFilter != null)
{
Application.RemoveMessageFilter(this.splitterMessageFilter);
this.splitterMessageFilter = null;
}
if (accept)
this.ApplySplitPosition();
else if (this.splitSize != this.initTargetSize)
this.SplitPosition = this.initTargetSize;
this.anchor = Point.Empty;
}
private void SplitMove(int x, int y)
{
int splitSize = this.GetSplitSize((x - base.Left) + this.anchor.X, (y - base.Top) + this.anchor.Y);
if (this.splitSize != splitSize)
{
this.splitSize = splitSize;
this.DrawSplitBar(2);
}
}
public override string ToString()
{
string str = base.ToString();
string[] textArray1 = new string[] { str, ", MinExtra: ", this.MinExtra.ToString(CultureInfo.CurrentCulture), ", MinSize: ", this.MinSize.ToString(CultureInfo.CurrentCulture) };
return string.Concat(textArray1);
}
[DefaultValue(0)]
[Category("Appearance")]
[Description("The border type of the control.")]
public System.Windows.Forms.BorderStyle BorderStyle
{
get
{
return this.borderStyle;
}
set
{
if (!IsEnumValid(value, (int)value, 0, 2))
throw new InvalidEnumArgumentException("value", (int)value, typeof(System.Windows.Forms.BorderStyle));
if (this.borderStyle != value)
{
this.borderStyle = value;
base.UpdateStyles();
}
}
}
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams createParams = base.CreateParams;
createParams.ExStyle &= -513;
createParams.Style &= -8388609;
System.Windows.Forms.BorderStyle borderStyle = this.borderStyle;
if (borderStyle != System.Windows.Forms.BorderStyle.FixedSingle)
{
if (borderStyle == System.Windows.Forms.BorderStyle.Fixed3D)
{
createParams.ExStyle |= 0x200;
}
return createParams;
}
createParams.Style |= 0x800000;
return createParams;
}
}
protected override Cursor DefaultCursor
{
get
{
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
return Cursors.HSplit;
case DockStyle.Left:
case DockStyle.Right:
return Cursors.VSplit;
}
return base.DefaultCursor;
}
}
protected override System.Windows.Forms.ImeMode DefaultImeMode
{
get
{
return System.Windows.Forms.ImeMode.Disable;
}
}
protected override Size DefaultSize
{
get { return new Size(3, 3); }
}
[Localizable(true), DefaultValue(3)]
public override DockStyle Dock
{
get { return base.Dock; }
set
{
if (((value != DockStyle.Top) && (value != DockStyle.Bottom)) && ((value != DockStyle.Left) && (value != DockStyle.Right)))
throw new ArgumentException("Splitter control must be docked left, right, top, or bottom.");
int splitterThickness = this.splitterThickness;
base.Dock = value;
switch (this.Dock)
{
case DockStyle.Top:
case DockStyle.Bottom:
if (this.splitterThickness == -1)
break;
base.Height = splitterThickness;
return;
case DockStyle.Left:
case DockStyle.Right:
if (this.splitterThickness != -1)
base.Width = splitterThickness;
break;
default:
return;
}
}
}
private bool Horizontal
{
get
{
DockStyle dock = this.Dock;
if (dock != DockStyle.Left)
return (dock == DockStyle.Right);
return true;
}
}
[Category("Behavior")]
[Localizable(true)]
[DefaultValue(25)]
[Description("Specifies the minimum size of the undocked area.")]
public int MinExtra
{
get { return this.minExtra; }
set
{
if (value < 0)
value = 0;
this.minExtra = value;
}
}
[Category("Behavior")]
[Localizable(true)]
[DefaultValue(25)]
[Description("Specifies the minimum size of the control being resized.")]
public int MinSize
{
get { return this.minSize; }
set
{
if (value < 0)
value = 0;
this.minSize = value;
}
}
[Category("Layout")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The current position of the splitter, or -1 if it is not bound to a control.")]
public int SplitPosition
{
get
{
if (this.splitSize == -1)
{
this.splitSize = this.CalcSplitSize();
}
return this.splitSize;
}
set
{
SplitData data = this.CalcSplitBounds();
if (value > this.maxSize)
{
value = this.maxSize;
}
if (value < this.minSize)
{
value = this.minSize;
}
this.splitSize = value;
this.DrawSplitBar(3);
if (data.target == null)
{
this.splitSize = -1;
}
else
{
Rectangle bounds = data.target.Bounds;
switch (this.Dock)
{
case DockStyle.Top:
bounds.Height = value;
break;
case DockStyle.Bottom:
bounds.Y += bounds.Height - this.splitSize;
bounds.Height = value;
break;
case DockStyle.Left:
bounds.Width = value;
break;
case DockStyle.Right:
bounds.X += bounds.Width - this.splitSize;
bounds.Width = value;
break;
}
data.target.Bounds = bounds;
Application.DoEvents();
this.OnSplitterMoved(new SplitterEventArgs(base.Left, base.Top, base.Left + (bounds.Width / 2), base.Top + (bounds.Height / 2)));
}
}
}
private class SplitData
{
public int dockHeight = -1;
public int dockWidth = -1;
internal Control target;
}
private class SplitterMessageFilter : IMessageFilter
{
private MySplitter owner;
public SplitterMessageFilter(MySplitter splitter)
{
this.owner = splitter;
}
public bool PreFilterMessage(ref Message m)
{
if ((m.Msg < 0x100) || (m.Msg > 0x108))
{
return false;
}
if ((m.Msg == 0x100) && (((int)((long)m.WParam)) == 0x1b))
{
this.owner.SplitEnd(false);
}
return true;
}
}
private static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue)
{
return ((value >= minValue) && (value <= maxValue));
}
}
public class MySplitterDesigner : ControlDesigner
{
public MySplitterDesigner() { base.AutoResizeHandles = true; }
private void DrawBorder(Graphics graphics)
{
Color white;
Control control = this.Control;
Rectangle clientRectangle = control.ClientRectangle;
if (control.BackColor.GetBrightness() < 0.5)
white = Color.White;
else
white = Color.Black;
using (Pen pen = new Pen(white))
{
pen.DashStyle = DashStyle.Dash;
clientRectangle.Width--;
clientRectangle.Height--;
graphics.DrawRectangle(pen, clientRectangle);
}
}
protected override void OnPaintAdornments(PaintEventArgs pe)
{
base.OnPaintAdornments(pe);
if (((MySplitter)base.Component).BorderStyle == BorderStyle.None)
this.DrawBorder(pe.Graphics);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x47)
this.Control.Invalidate();
base.WndProc(ref m);
}
}
Here is highlight form:
public class HighLight : Form
{
public HighLight()
{
FormBorderStyle = FormBorderStyle.None;
BackColor = Color.Black;
Opacity = 0;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
}
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
this.Hide();
}
private const int SW_SHOWNOACTIVATE = 4;
private const int HWND_TOPMOST = -1;
private const uint SWP_NOACTIVATE = 0x0010;
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
static extern bool SetWindowPos(int hWnd, int hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public void ShowInactiveTopmost()
{
ShowWindow(this.Handle, SW_SHOWNOACTIVATE);
SetWindowPos(this.Handle.ToInt32(), HWND_TOPMOST,
this.Left, this.Top, this.Width, this.Height,
SWP_NOACTIVATE);
this.Opacity = 0.3;
}
}

Collision between circle and a radius

I need to implement collision detection here. The objects i have here are a ball/circle and a rectangle. The balls are moving vertically, while the rectangle is moving horizontally. The condition is that if the ball and rectangle touch each other then an event should be raised. I have been trying to do that for a while with my colleague but without success. This is my first program in C# so please bear with me.
here is my code:
public partial class Form1 : Form
{
bool collided = false;
Player player;
List<Ball> balls;
const int fps = 60;
public Form1()
{
InitializeComponent();
balls = new List<Ball>();
Random r = new Random();
for(int i =0; i<1;i ++)
{
balls.Add(new Ball(Width, Height,r));
}
var task = new Task(Run);
task.Start();
player = new Player()
{
x = this.Width/2,
y = (Height*9/10),
xvel = 10,
brush = Brushes.Black,
};
}
protected void Run()
{
while (true)
{
for(int i = 0; i < balls.Count; i++)
{
balls[i].Move(this.Width);
}
this.Invalidate();
Thread.Sleep(1000 / fps);
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(Color.White);
for(int i = 0; i < balls.Count; i++)
{
balls[i].Draw(g);
}
player.DrawPlayer(g);
}
//This is the part where i was trying to check collision between the circle and a ball
private void CheckCollision(PaintEventArgs e)
{
if (player.IntersectsWith(balls))
{
player.Intersect(balls);
if (!player.IsEmpty)
{
collided = true;
MessageBox.Show("collision detected");
}
}
}
}
public class Player
{
public float x, y, xvel;
public Brush brush;
public Player()
{
}
public void DrawPlayer(Graphics g)
{
g.FillRectangle(brush, new RectangleF(x, y, 30,30));
}
public void MovePlayerLeft(int gameWidth)
{
if (x > 0)
{
x -= xvel;
}
}
public void MovePlayerRight(int gameWidth)
{
if (x < gameWidth-47)
{
x += xvel;
}
}
}
public class Ball
{
public float x, y, yvel, radius;
public Brush brush;
public Ball(int gamewidth,int gameHeight,Random r)
{
x = r.Next(gamewidth);
y = r.Next(gameHeight);
yvel = r.Next(2) + 5;
radius = r.Next(10) + 5;
brush = new SolidBrush(Color.Blue);
}
public void Move(int gameHeight)
{
if (y + radius >= gameHeight)
{
y = 0;
}
y += yvel;
}
public void Draw(Graphics g)
{
g.FillEllipse(brush, new RectangleF(x-radius,y - radius, radius * 2, radius * 2));
}
}
If you're trying to figure out if a rectangle and a circle is intersecting, try this algorithm for each of the four sides:
Circle line-segment collision detection algorithm?
You can probably speed this up by checking if corners are inside the circle.
Also, remember that a circle completely inside a rectangle and vice versa should probably count as a collision.

Categories

Resources