I have a little trouble with my health. When I was moving my personage, the healthbar lasped out of screen.
How can I keep it standing in my screen,something likes not moving anywhere. But when I move my personage, it'll move, too.
Here my code:
private Texture2D container, lifebar;
public Vector2 position;
public int fullHealth;
public int currentHealth;
public Healthbar(ContentManager content)
{
LoadContent(content);
fullHealth = lifebar.Width;
currentHealth = fullHealth;
}
private void LoadContent(ContentManager content)
{
container = content.Load<Texture2D>("Untitled");
lifebar = content.Load<Texture2D>("Health 2");
}
public void Update()
{
if (Keyboard.GetState().IsKeyDown(Keys.Right))
position.X += 3;
if (Keyboard.GetState().IsKeyDown(Keys.Left))
position.X -= 3;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(container, position ,Color.Red);
spriteBatch.Draw(lifebar, position, new Rectangle((int)position.X, (int)position.Y, currentHealth, lifebar.Height), Color.Pink);
}
You need to check the position.x and position.y values with the screen bounds otherwise you will always lose the health bar. You want something like:
if (position.X <= 10)
position.X = 10;
if (position.X >= 1270)
position.X = 1270;
etc.
Related
I want to create a camera movement like idle miner tycoon. So the Camera should scroll vertically by panning with a typically scroll effect.
This is my code:
Vector3 touchStart;
public int upperLimit = 0;
public int lowerLimit = 7000;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButton(0))
{
Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
float finalYPos = Camera.main.transform.position.y + direction.y;
finalYPos = Mathf.Clamp(finalYPos, lowerLimit, upperLimit);
Camera.main.transform.position = new Vector3(Camera.main.transform.position.x, finalYPos, Camera.main.transform.position.z);
Debug.Log(finalYPos);
}
}
But how can I make that the scrolling is ran out. Actually the movement is stopping directly when I leave the mouse/thump.
Thank you for your help
Best regards
I found a Solution for everybody with the same problem:
[SerializeField]
private Camera cam;
Vector3 touchStart;
private float topLimit = 0f;
private float bottomLimit = -2000.0f;
private Vector3 _curPosition;
private Vector3 _velocity;
private bool _underInertia;
private float _time = 0.0f;
public float SmoothTime = 2;
public Vector3 direction;
void Update()
{
PanCamera();
if (_underInertia && _time <= SmoothTime)
{
cam.transform.position += _velocity;
float newY = Mathf.Clamp(cam.transform.position.y, bottomLimit, topLimit);
cam.transform.position = new Vector3(cam.transform.position.x, newY, cam.transform.position.z);
_velocity = Vector3.Lerp(_velocity, Vector3.zero, _time);
_time += Time.smoothDeltaTime;
}
else
{
_underInertia = false;
_time = 0.0f;
}
}
private void PanCamera()
{
if (Input.GetMouseButtonDown(0))
{
touchStart = cam.ScreenToWorldPoint(Input.mousePosition);
_underInertia = false;
}
if (Input.GetMouseButton(0))
{
Vector3 _prevPosition = _curPosition;
direction = touchStart - cam.ScreenToWorldPoint(Input.mousePosition);
float finalYPos = cam.transform.position.y + direction.y;
Debug.Log("Old: " + finalYPos);
finalYPos = Mathf.Clamp(finalYPos, bottomLimit, topLimit);
Debug.Log("New: " + finalYPos);
Vector3 desiredPosition = new Vector3(cam.transform.position.x, finalYPos, cam.transform.position.z);
cam.transform.position = desiredPosition;
_curPosition = desiredPosition;
_velocity = _curPosition - _prevPosition;
}
if (Input.GetMouseButtonUp(0))
{
_underInertia = true;
}
}
When the player hits the ground the camera shakes and when he jumps he just get's teleported up in an unsmooth manner
public class PlayerController : MonoBehaviour {
CharacterController controller;
Vector3 motion = Vector3.zero;
#region Movement Variables
public float walkingSpeed = 4f;
public float runningSpeed = 6f;
public float jumpSpeed = 5f;
public float gravity = 9.8f;
#endregion Movement Variables
void Start () {
controller = GetComponent<CharacterController>();
}
void Update () {
motion = Vector3.zero;
motion.x = Input.GetAxis("Horizontal");
if (controller.isGrounded && Input.GetAxis("Vertical")>0) motion.y += jumpSpeed;
if (Input.GetKey(KeyCode.LeftShift))
{
motion.x *= runningSpeed;
}
else
{
motion.x *= walkingSpeed;
}
motion.y -= gravity;
}
void FixedUpdate()
{
controller.Move(motion * Time.deltaTime);
}
}
I'm trying to create smooth movement and currently it is not reliable at all. thanks for any helpers
Take controller.Move(motion * Time.deltaTime); out of FixedUpdate and put it at the very end of Update method.
In case you have some script on camera as well, for example, some implementation of a follow camera where you're working with the transform component of that camera in the Update loop, that should go in LateUpdate instead.
See this https://learn.unity.com/tutorial/update-and-fixedupdate#5c8a4242edbc2a001f47cd63
and https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html
This implementation of a player controller for GameObject that has a Character Controller component may also help you.
void Update()
{
if (isDead) return;
isWalking = Input.GetButton("Walk");
isGrounded = characterController.isGrounded;
if (isGrounded)
{
// Move
float verticalAxis = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, verticalAxis);
moveDirection = transform.TransformDirection(moveDirection);
if (verticalAxis > 0 && isWalking)
{
moveDirection *= walkingSpeed;
}
else if (verticalAxis > 0)
{
moveDirection *= runningSpeed;
}
// Jump
if (Input.GetButtonDown("Jump"))
{
moveDirection.y = jumpSpeed;
//moveDirection.z = jumpDistance; in case some forward boost is required
moveDirection = transform.TransformDirection(moveDirection);
}
}
// Gravity
moveDirection.y -= gravity * Time.deltaTime;
characterController.Move(moveDirection * Time.deltaTime);
// Rotation
float horizontalAxis = Input.GetAxis("Horizontal");
transform.Rotate(0, horizontalAxis, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.FromToRotation(transform.up, GetHitNormal()) * transform.rotation, yRotationSpeed * Time.deltaTime);
}
// To keep local up aligned with global up on a slope ground
private Vector3 GetHitNormal()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit))
return hit.normal;
else
return Vector3.zero;
}
I am trying to use code gathered off of this website to make an application that bounces circles around. when i click now - it creates a circle that just seems to vibrate in place and does not bounce off of the borders.
HERE IS THE CODE HAT SOLLVED MY ISSUE THANKS GUYS
#FXML
private AnchorPane anchorPane;
#FXML
private Label ballCountLabel;
public int ballCount = 0;
public int mouseClick = 0;
Circle[] balls = new Circle[1000];
#Override
public void initialize(URL url, ResourceBundle rb) {
pane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane.setTopAnchor(pane, 0.0);
AnchorPane.setLeftAnchor(pane, 0.0);
AnchorPane.setTopAnchor(pane, 0.0);
AnchorPane.setRightAnchor(pane, 0.0);
}
#FXML
private void mouseAddBall(MouseEvent event) throws Exception {
balls[mouseClick] = new Circle(15, Color.BLANCHEDALMOND);
balls[mouseClick].relocate(event.getSceneX(), event.getSceneY());
pane.getChildren().add(balls[mouseClick]);
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);
addBallMovement(balls[mouseClick]);
mouseClick++;
}
public void addBallMovement(Circle b){
final Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {
double deltaX = 3;
double deltaY = 3;
#Override
public void handle(ActionEvent t) {
b.setLayoutX(b.getLayoutX() + deltaX);
b.setLayoutY(b.getLayoutY() + deltaY);
final Bounds bounds = pane.getBoundsInParent();
final boolean atRightBorder = b.getLayoutX() >= (bounds.getMaxX() - b.getRadius());
final boolean atLeftBorder = b.getLayoutX() <= (bounds.getMinX() + b.getRadius());
final boolean atBottomBorder = b.getLayoutY() >= (bounds.getMaxY() - b.getRadius());
final boolean atTopBorder = b.getLayoutY() <= (bounds.getMinY() + b.getRadius());
if (atRightBorder || atLeftBorder) {
deltaX *= -1;
}
if (atBottomBorder || atTopBorder) {
deltaY *= -1;
}
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
I changed Ball to Circle to test your code. You are changing to the next ball in the balls array before you add movement to the current ball. This is probably giving you a NullPointerException.
Change
balls[mouseClick] = new Circle(event.getSceneX(), event.getSceneY(),
Math.random() * 20);
pane.getChildren().add(balls[mouseClick]);
mouseClick++;
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);
addBallMovement(balls[mouseClick]); //<--You want to move the current ball. This code needs to be before mouseClick++
To:
balls[mouseClick] = new Circle(event.getSceneX(), event.getSceneY(),
Math.random() * 20);
pane.getChildren().add(balls[mouseClick]);
addBallMovement(balls[mouseClick]);
mouseClick++;
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);
Few days before, I asked you to help me because I couldn't show the drawing of a circle pixel by pixel (the drawing got stuck). #James_D found the solution and told me it was because a background-thread was trying to modify the UI. Indeed, I have a GraphicEngine class that extends Service : this class is this background-thread and its aim was to calculate and modify the image (now its aim is just to calculate the circle's pixels).
Well, finally, thanks to #James_D, I have now some classes :
GraphicEngine,
ImageAnimation which contains the animation of drawing,
DialogCreationOfCircularGradation, which is a dialog containing a button "OK, draw circle !" and which handles this event.
The below source contains the answer of my program to the user-event "Draw a circle". It gets several Textfield's input and give it to the GraphicsEngine. Moreover it asks the latter to do the calculation of the circle's pixels and asks the ImageAnimation to display the calculation pixel by pixel, during the calculation done by the GraphicsEngine.
CLASS DialogCreationOfCircularGradation
public void dialogHandleEvents() {
Optional r = this.showAndWait();
if(r.isPresent() && r.get() == ButtonType.OK) { // The user clicks on "OK, draw the circle !"
int radius = Integer.parseInt(this.dialog_field_radius.getText());
[...]
this.gui.getImageLoader().loadImageFromUsersPreferences(x0 + thickness + 2*radius, y0 + thickness + 2*radius);
this.gui.getGraphicEngine().setOperationToDo("Circle");
this.gui.getGraphicEngine().setRadius(radius);
[...]
this.gui.getGraphicEngine().restart();
this.gui.getImageAnimation().start();
}
}
The below code is GraphicsEngine's one. As you can see, there is in particular one important variable which is incremented during the circle algorithm : its name is counter_max. Why this variable is important ? Because it's necessary used in the class ImageAnimation. Look at its source after GraphicsEngine's one.
CLASS GraphicEngine
public class GraphicEngine extends Service<Void> {
private int image_width, image_height;
private PixelReader pixel_reader;
private BlockingQueue<Pixel> updates;
private String operation_to_do;
private int radius; [...]
public void setOperationToDo(String operation_to_do) {
this.operation_to_do = operation_to_do;
}
public Task<Void> createTask() {
return new Task<Void>() {
protected Void call() {
switch(operation_to_do) {
[...]
case "Circle" :
traceCircularGradation();
break;
}
return null;
}
};
}
private void traceCircularGradation() {
double w = 2 * 3.141, precision = 0.001;
long counter_max = 0;
int x, y;
this.gui.getImageAnimation().setMax(counter_max);
double[] rgb_gradation;
for (double current_thickness = 0; current_thickness <= this.thickness; current_thickness++) {
for (double angle = 0; angle <= w; angle += precision) {
x = (int) ((current_thickness + radius) * Math.cos(angle) + x0);
y = (int) ((current_thickness + radius) * Math.sin(angle) + y0);
if(x >= 0 && y >= 0) {
counter_max++;
rgb_gradation = PhotoRetouchingFormulas.chromatic_gradation(angle, w);
updates.add(new Pixel(x, y, Color.color(rgb_gradation[0], rgb_gradation[1], rgb_gradation[2])));
}
}
}
this.gui.getImageAnimation().setMax(counter_max);
}
The variable counter_max is used in ImageAnimation (its name has changed, its called : max). It's useful in the last if : if (count >= max).
max/counter_max represent the number of modified pixels. I can't replace it with image_width * image_height because in the circle algorithm, only the circle's pixels are drawn/modified. The other pixels of the image are not.
So I have either to compute counter_max as I did here in the for loops and then give it to ImageAnimation, or find a mathematical formula to determine it before the for. In the first case, the display of the circle doesn't work.
It would be really perfect if a formula existed.
CLASS ImageAnimation
public class ImageAnimation extends AnimationTimer {
private Gui gui;
private long max;
private long count, start;
ImageAnimation (Gui gui) {
this.gui = gui;
this.count = 0;
this.start = -1;
}
public void setMax(long max) {
this.max = max;
}
#Override
public void handle(long timestamp) {
if (start < 0) {
start = timestamp ;
return ;
}
WritableImage writable_image = this.gui.getWritableImage();
BlockingQueue<Pixel> updates = this.gui.getUpdates();
while (timestamp - start > (count* 5_000_000) / (writable_image.getWidth()) && ! updates.isEmpty()) {
Pixel update = updates.remove();
count++;
writable_image.getPixelWriter().setColor(update.getX(), update.getY(), update.getColor());
}
if (count >= max) {
this.count = 0;
this.start = -1;
stop();
}
}
public void startAnimation() {
this.start();
}
}
If you need to compute max later, then you can't initialize it to zero (because if you do any updates before it is set to its "correct" value, then count will exceed max and you will stop the animation). So just initialize it to something it will never reach, e.g. Long.MAX_VALUE.
Relatedly, since you are accessing max from multiple threads, you should either synchronize access to it, or (better) use an AtomicLong. I.e.
public class ImageAnimation extends AnimationTimer {
private Gui gui;
private AtomicLong max;
private long count, start;
ImageAnimation (Gui gui) {
this.gui = gui;
this.count = 0;
this.start = -1;
this.max = new AtomicLong(Long.MAX_VALUE);
}
public void setMax(long max) {
this.max.set(max);
}
#Override
public void handle(long timestamp) {
if (start < 0) {
start = timestamp ;
return ;
}
WritableImage writable_image = this.gui.getWritableImage();
BlockingQueue<Pixel> updates = this.gui.getUpdates();
while (timestamp - start > (count* 5_000_000) / (writable_image.getWidth()) && ! updates.isEmpty()) {
Pixel update = updates.remove();
count++;
writable_image.getPixelWriter().setColor(update.getX(), update.getY(), update.getColor());
}
if (count >= max.get()) {
this.count = 0;
this.start = -1;
this.max.set(Long.MAX_VALUE);
stop();
}
}
public void startAnimation() {
this.start();
}
}
I am calling invalidate() which is calling onDraw(). The bitmap that I wish to show on the screen is not being displayed after running doInBackGround(). Can anyone help?
Here is what I have tested out so far.
When I place the same line of code
canvas.drawBitmap();
in onPreExecute() it works, but in onPostExecute() it does not display the expected results.
This is my code:
public class FloorAppActivity extends Activity {
private Context globalContext;
private Point displaySize;
private int displayWidth;
private int displayHeight;
private String floorID;
private String floorName;
private String floorGridNumStr;
private int floorGridNum;
private String floorNumStr;
private int positionX;
private int positionY;
private int XCoord;
private int YCoord;
private int ZCoord;
private float signalStr;
private Integer dBm;
private Bitmap floorPlan;
private Bitmap userMark;
private Bitmap redPin;
private FloorView floorView;
private Connection conn = null;
private Canvas canvas=null;
private int newScrollRectX=0;
private int newScrollRectY=0;
private Paint paint;
private boolean a = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
globalContext = this;
floorID = getIntent().getStringExtra("floorID");
floorName = getIntent().getStringExtra("floorName");
positionX = getIntent().getIntExtra("userPositionX",-1);
positionY = getIntent().getIntExtra("userPositionY",-1);
dBm = getIntent().getIntExtra("BestSignal", -1);
//Get the grid number
if(Integer.parseInt(floorName.substring(floorName.lastIndexOf("_")+1))<10)
floorGridNumStr = floorName.substring(8, 9);
else
floorGridNumStr = floorName.substring(8, 10);
floorGridNum = Integer.parseInt(floorGridNumStr);
floorNumStr = floorName.substring(5,7);
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
displaySize = new Point();
try {
// GetSize is not available in older models of Android
display.getSize(displaySize);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
displaySize.x = display.getWidth();
displaySize.y = display.getHeight();
}
try {
InputStream source = getAssets().open(floorID);
floorPlan = BitmapFactory.decodeStream(source);
displayWidth = Math.min(displaySize.x, floorPlan.getWidth());
displayHeight = Math.min(displaySize.y, floorPlan.getHeight());
userMark = BitmapFactory.decodeResource(getResources(),R.drawable.star);
redPin = BitmapFactory.decodeResource(getResources(),R.drawable.redpin);
floorView = new FloorView(this);
setContentView(floorView);
}
catch (IOException e) {
MapServerAPI server = new MapServerAPI(globalContext,"Retrieving floor plan. Please wait...") {
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap == null)
Toast.makeText(globalContext, "Error in retrieving floor plan!", Toast.LENGTH_LONG).show();
else {
floorPlan = bitmap;
displayWidth = Math.min(displaySize.x, floorPlan.getWidth());
displayHeight = Math.min(displaySize.x, floorPlan.getHeight());
userMark = BitmapFactory.decodeResource(getResources(),R.drawable.star);
redPin = BitmapFactory.decodeResource(getResources(),R.drawable.redpin);
floorView = new FloorView(globalContext);
setContentView(floorView);
}
}
};
server.execute(floorID);
}
}
#Override
public void onResume() {
super.onResume();
registerReceiver(broadcastReceiver,new IntentFilter("FingerPrint_LOCATION_UPDATE"));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
// listen for user location change
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String result = intent.getStringExtra("location");
Toast.makeText(context,result,Toast.LENGTH_LONG).show();
String floorId = intent.getStringExtra("floorID");
floorName = intent.getStringExtra("name");
dBm = intent.getIntExtra("BestSignal", -1);
int userLocationX = intent.getIntExtra("userPositionX",-1);
int userLocationY = intent.getIntExtra("userPositionY",-1);
//Get the grid number
if(Integer.parseInt(floorName.substring(floorName.lastIndexOf("_")+1))<10)
floorGridNumStr = floorName.substring(8, 9);
else
floorGridNumStr = floorName.substring(8, 10);
floorGridNum = Integer.parseInt(floorGridNumStr);
floorNumStr = floorName.substring(5,7);
if(!floorId.equals(floorID)){
positionX = userLocationX;
positionY = userLocationY;
InputStream source=null;
try {
source = getAssets().open(floorID);
} catch (IOException e) {
}
floorPlan = BitmapFactory.decodeStream(source);
floorView.postInvalidate();
}
}
};
private class FloorView extends View {
private Rect displayRect; //rect we display to
private Rect scrollRect; //rect we scroll over our bitmap with
private int scrollRectX = 0; //current left location of scroll rect
private int scrollRectY = 0; //current top location of scroll rect
private float scrollByX = 0; //x amount to scroll by
private float scrollByY = 0; //y amount to scroll by
private float startX = 0; //track x from one ACTION_MOVE to the next
private float startY = 0; //track y from one ACTION_MOVE to the next
public FloorView(Context context) {
super(context);
// Destination rect for our main canvas draw. It never changes.
displayRect = new Rect(0, 0, displayWidth, displayHeight);
// Scroll rect: this will be used to 'scroll around' over the
// bitmap in memory.
if (positionX + displayWidth / 2 > floorPlan.getWidth())
scrollRectX = floorPlan.getWidth() - displayWidth;
else
scrollRectX = positionX - displayWidth / 2;
if (scrollRectX < 0)
scrollRectX = 0;
if (positionY + displayHeight / 2 > floorPlan.getHeight())
scrollRectY = floorPlan.getHeight() - displayHeight;
else
scrollRectY = positionY - displayHeight / 2;
if (scrollRectY < 0)
scrollRectY = 0;
scrollRect = new Rect(scrollRectX, scrollRectY, displayWidth, displayHeight);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Remember our initial down event location.
startX = event.getRawX();
startY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
float x = event.getRawX();
float y = event.getRawY();
// Calculate move update. This will happen many times
// during the course of a single movement gesture.
scrollByX = x - startX; //move update x increment
scrollByY = y - startY; //move update y increment
startX = x; //reset initial values to latest
startY = y;
invalidate(); //force a redraw
break;
}
return true; //done with this event so consume it
}
#Override
protected void onDraw(Canvas canvas1) {
canvas=canvas1;
// Our move updates are calculated in ACTION_MOVE in the opposite direction
// from how we want to move the scroll rect. Think of this as dragging to
// the left being the same as sliding the scroll rect to the right.
newScrollRectX = scrollRectX - (int)scrollByX;
newScrollRectY = scrollRectY - (int)scrollByY;
// Don't scroll off the left or right edges of the bitmap.
if (newScrollRectX < 0)
newScrollRectX = 0;
else if (newScrollRectX > (floorPlan.getWidth() - displayWidth))
newScrollRectX = (floorPlan.getWidth() - displayWidth);
// Don't scroll off the top or bottom edges of the bitmap.
if (newScrollRectY < 0)
newScrollRectY = 0;
else if (newScrollRectY > (floorPlan.getHeight() - displayHeight))
newScrollRectY = (floorPlan.getHeight() - displayHeight);
// We have our updated scroll rect coordinates, set them and draw.
scrollRect.set(newScrollRectX, newScrollRectY,
newScrollRectX + displayWidth, newScrollRectY + displayHeight);
paint = new Paint();
canvas.drawBitmap(floorPlan, scrollRect, displayRect, paint);
// Update user position
if (positionX >= newScrollRectX && positionX - newScrollRectX <= displayWidth
&& positionY >= newScrollRectY && positionY - newScrollRectY <= displayHeight)
canvas.drawBitmap(userMark,positionX-newScrollRectX-userMark.getWidth()/2,positionY-newScrollRectY-userMark.getHeight()/2,paint);
class AsyncTaskToConnect extends AsyncTask <Void, Void, Void>{
#Override
protected Void doInBackground(Void... cmd) {
// connect to database and retrieve values
return null;
}
#Override
protected void onPostExecute(Void v)
{//PE
if (positionX >= newScrollRectX && positionX - newScrollRectX <= displayWidth
&& positionY >= newScrollRectY && positionY - newScrollRectY <= displayHeight)
{
canvas.drawBitmap(redPin,480-newScrollRectX-userMark.getWidth()/2,90-newScrollRectY-userMark.getHeight()/2,paint);
}
//return null;
// Reset current scroll coordinates to reflect the latest updates,
// so we can repeat this update process.
scrollRectX = newScrollRectX;
scrollRectY = newScrollRectY;
}//PE
}
AsyncTaskToConnect[] asyncTaskC = null;
asyncTaskC = new AsyncTaskToConnect[1];
asyncTaskC[0] = new AsyncTaskToConnect();
asyncTaskC[0].executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// Cache our new dimensions; we'll need them for drawing.
displayWidth = Math.min(w, floorPlan.getWidth());
displayHeight = Math.min(h, floorPlan.getHeight());
// Destination rect for our main canvas draw.
displayRect = new Rect(0, 0, displayWidth, displayHeight);
// Scroll rect: this will be used to 'scroll around' over the
// bitmap in memory.
if (positionX + displayWidth / 2 > floorPlan.getWidth())
scrollRectX = floorPlan.getWidth() - displayWidth;
else
scrollRectX = positionX - displayWidth / 2;
if (scrollRectX < 0)
scrollRectX = 0;
if (positionY + displayHeight / 2 > floorPlan.getHeight())
scrollRectY = floorPlan.getHeight() - displayHeight;
else
scrollRectY = positionY - displayHeight / 2;
if (scrollRectY < 0)
scrollRectY = 0;
scrollRect = new Rect(scrollRectX, scrollRectY, displayWidth, displayHeight);
super.onSizeChanged(w, h, oldw, oldh);
}
}
}
P.S. This is my first time posting. Please pardon me if i make mistakes in my post. Thanks.
I think the problem is that you are storing the Canvas object passed into the onDraw method. The object may not be valid after the onDraw method has returned.
It looks like you are trying to prepare a Bitmap on a background thread and then draw it on screen when it has been prepared. The way you do it is - prepare the Bitmap and just call invalidate on the View in onPostExecute method. Then in the onDraw method, you can take that Bitmap object and draw it using canvas.drawBitmap