MonoTouch: How to resize a view.Frame inside Draw override and draw correctly? - xamarin.ios

the problem I am having it that if inside the UIView Draw override, I change the view frame size, drawing a rectangle is not working as expected.
If I change the view frame size outside of the Draw override, it works fine. Is this an expected behavior or is it a problem with monotouch only?
This is the code I am using:
class ChildView : UIView
{
public override void Draw (RectangleF rect)
{
base.Draw (rect);
CGContext g = UIGraphics.GetCurrentContext();
//adding 30 points to view height
RectangleF rec = new RectangleF(this.Frame.Location,this.Frame.Size);
rec.Height+=30;
RectangleF rec_bounds = new RectangleF(0,0,rec.Width,rec.Height);
this.Frame=rec;
this.Bounds=rec_bounds;
//drawing a red rectangle to the first half of view height
UIColor.Red.SetFill();
RectangleF _rect = new RectangleF(this.Bounds.Location,this.Bounds.Size);
_rect.Height=_rect.Height/2;
g.FillRect(_rect);
}
}
However, the output of this code is this: (it should draw only 30 points red, but it draws 60 points)
Here is a link to download the project to reproduce this issue:
www.grbytes.com\downloads\RectangleDrawProblem.rar

Καλημέρα!
This behavior is expected. If you want to change the view's frame inside the Draw override, do it before getting the current context. That is because the graphics context also has a size and that is the size of the view at the time you are retrieving it.
Also, there is no need to set both the Bounds and the Frame of the view. You can just set either of them in this case.

By the way, I don't think you need to call base.Draw(). According to the Apple documentation, "If you subclass UIView directly, your implementation of this method does not need to call super."

Related

SWT Canvas fails to redraw on Windows but works on Linux

this.canvas = new Canvas(shell, SWT.NO_BACKGROUND);
I'm using a PaintListener:
this.canvas.addPaintListener(new PaintListener() {
#Override
public void paintControl(PaintEvent e) {
// Draw images
synchronized (imageMarks) {
for (ImageMark mark : Whiteboard.this.imageMarks)
{
Image image = Whiteboard.this.getImage(mark.id);
Point position = ScaledPoint.toSWTPoint(Whiteboard.this.getCanvasSize(), mark.getPosition());
Point bounds = mark.getUnscaledBoundaries(Whiteboard.this.getCanvasSize());
e.gc.drawImage(image, 0, 0, image.getBounds().width, image.getBounds().height, position.x, position.y,
bounds.x, bounds.y);
}
}
// Draw pencil marks
synchronized (pencilMarks) {
e.gc.setLineWidth(LINE_WIDTH);
for (double[] line : Whiteboard.this.pencilMarks)
{
Point lastPosPoint = ScaledPoint.toSWTPoint(Whiteboard.this.getCanvasSize(), new ScaledPoint(line[0], line[2]));
Point newPosPoint = ScaledPoint.toSWTPoint(Whiteboard.this.getCanvasSize(), new ScaledPoint(line[1], line[3]));
e.gc.drawLine(lastPosPoint.x, lastPosPoint.y, newPosPoint.x, newPosPoint.y);
}
}
// Draw pointer, assuming it's there
if (pointerMark != null)
{
synchronized (pointerMark) {
Point pos = ScaledPoint.toSWTPoint(Whiteboard.this.getCanvasSize(), pointerMark.getPosition());
if (pointerMark.isFlipped())
e.gc.drawImage(Whiteboard.pointerImageFlipped, pos.x, pos.y);
else
e.gc.drawImage(Whiteboard.pointerImage, pos.x, pos.y);
}
}
}
});
and redrawing the canvas via a canvas.redraw() call. On 64-bit Linux, this seems to be working without any issues, but strangely enough, on 64-bit Windows, nothing ever ends up being erased or redrawn. For example, if the screen is resized, the pencil markings do not resize as well, they just end up being cut out of the screen. When new marks are added (in other words, when the paint listener is called again), the repositioned markings are redrawn on top of the old ones which didn't scale with the window. In other words, I believe the canvas is not being cleared upon canvas.redraw(). Is there a workaround for this?
You are specifying SWT.NO_BACKGROUND which stops the Canvas being cleared before each paint.
If you use SWT.NO_BACKGROUND it is your paint method's responsibility to draw every pixel of the Canvas.
SWT.NO_BACKGROUND JavaDoc:
By default, before a widget paints, the client area is filled with the
current background. When this style is specified, the background is
not filled, and the application is responsible for filling every pixel
of the client area. This style might be used as an alternative to
"double-buffering" in order to reduce flicker. This style does not
mean "transparent" - widgets that are obscured will not draw through.

When inflating a view in OnCreateView, is it supposed to have correct size right after creation?

I have a Fragment class which I use with Android.support.v4.view.ViewPager.
In the OnCreateView, that is called by the pager when it needs to display another page, I create a label and I want to dynamically set some font sizes inside that label to be a percentage of the label's height:
class LabelFragment : Android.Support.V4.App.Fragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var v = inflater.Inflate(Resource.Layout.Label, container, false);
float BigFontSize = v.Height / 1.5f;
float MediumFontSize = v.Height / 5.0f;
float SmallFontSize = v.Height / 10.0f;
// Setting font sizes for the children of v
return v;
}
}
When I wrote this code my understanding was that v will have correct Width and Height right after inflating.
Indeed, this works on the emulators and on some devices, but on some other devices the label child elements disappear because they get zero font size assigned, which means v.Height was zero.
Is this code valid? Is it documented whether the view returned by Inflate should have correct dimensions? Should I be taking height from container instead, and if so, is it documented that it will be non-null when used with ViewPager?
The problem is that the view has not yet been drawn in the OnCreateView method. So Height will most likely be an unexpected value.
OK, so what can you do to get the height of the view? Use ViewTreeObserver to get the PreDraw event like:
v.ViewTreeObserver.PreDraw += (s, e) =>
{
// do height calculations here
};
Also I noticed you are using font sizes, please make sure you are not using pixel heights for them and use a scaleable unit instead (sp). This is presumably why you are setting font size in the first place.

Retrieving a CGRect from a transformed CGContext and apply to a UIView

I am drawing a PDF page into a CGContext.
In order to properly draw it, I am applying some transformations to the context.
The pdf page rendered rect is smaller than the view's rect.
I want to create a third view that has exact same frame as the part of the view that has a pdf rendered.
My solution works, but not entirely. Sometimes (a lot of times) the rect is wrong.
This is what I am doing:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context {
CGContextSaveGState(context);
// apply transforms to context
// draw pdf page
CGRect calculatedFromRect = CGRectApplyAffineTransform(pageRect, CGContextGetCTM(context));
CGContextRestoreGState(context);
// now draw a green rect to test the frame on a not transformed context
GContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
CGContextFillRect(context, calculatedFromRect);
self.thirdView.frame = calculatedFromRect;
}
The thirdView is red. When both rects (view and drawing) are equal, I see a brown rect on the screen (red with alpha on top of the green rect). But sometimes I can see they two separated from each other (offset and size difference...when this happens, the thirdView.frame is bigger than calcularedRect).
Since all the involved views have the same size and coordinates, not converting the coordinates with convertRect:fromView: shouldn't be a problem. But I tried this and the result was the same.

Set scene width and height

I have been trying to set the scene's width and height outside of the constructor and it's been to no avail. After looking through the Scene API I saw a method that lets you get the height and width respectively but not one to set the method.. :s (design flaw maybe).
After further research I came across the SceneBuilder and found methods that could modify the height and width. However, I do not know how to apply it to a scene object already created or how to create a SceneBuilder object that could be used in place of the scene object.
Once you created Scene and assigned it to the Stage you can use Stage.setWidth and Stage.setHeight to change both stage and scene sizes simultaneously.
SceneBuilder can't be applied to an already created object, it can only be used for the scene creation.
It seems not possible to set the size of the Scene after it has been created.
Setting the size of the Stage means to set the size of the window, which includes the size of the decoration. So the Scene is smaller in size, unless the Stage is undecorated.
My solution is to compute the size of the decoration while initialization and add it to the size of the Stage when resizing:
private Stage stage;
private double decorationWidth;
private double decorationHeight;
public void start(Stage stage) throws Exception {
this.stage = stage;
final double initialSceneWidth = 720;
final double initialSceneHeight = 640;
final Parent root = createRoot();
final Scene scene = new Scene(root, initialSceneWidth, initialSceneHeight);
this.stage.setScene(scene);
this.stage.show();
this.decorationWidth = initialSceneWidth - scene.getWidth();
this.decorationHeight = initialSceneHeight - scene.getHeight();
}
public void resizeScene(double width, double height) {
this.stage.setWidth(width + this.decorationWidth);
this.stage.setHeight(height + this.decorationHeight);
}
I just wanted to post another answer for those who might have had a similar problem as mine.
http://docs.oracle.com/javase/8/javafx/api/javafx/scene/Scene.html
There is no setWidth() or setHeight(), and the property is ReadOnly, but if you look at
Constructors
Scene(Parent root)
Creates a Scene for a specific root Node.
Scene(Parent root, double width, double height)
Creates a Scene for a specific root Node with a specific size.
Scene(Parent root, double width, double height, boolean depthBuffer)
Constructs a scene consisting of a root, with a dimension of width and height, and specifies whether a depth buffer is created for this scene.
Scene(Parent root, double width, double height, boolean depthBuffer, SceneAntialiasing antiAliasing)
Constructs a scene consisting of a root, with a dimension of width and height, specifies whether a depth buffer is created for this scene and specifies whether scene anti-aliasing is requested.
Scene(Parent root, double width, double height, Paint fill)
Creates a Scene for a specific root Node with a specific size and fill.
Scene(Parent root, Paint fill)
Creates a Scene for a specific root Node with a fill.
As you can see, this is where you can set the height and width if you need to.
For me, I am using SceneBuilder, just as you described you were doing, and needed the width and height of that. I am creating custom controls, so it was weird that it didn't do it automatically, so this is how to do it if you need to.
I could have used setWidth() / setHeight() from the Stage as well.
I had an similar challenge when I wanted to switch between different size scenes in JavaFX.
I did my scene switching by changing the Parent resource of a Scene. The new resource would have larger dimensions than the previous resource so the entire Scene wasn't visible.
Like user2229691's answer stated - my issue turned out to be the Window not matching the Scene's dimensions.
Although I'm not able to comment about decorations - I was able to solve my issue by using:
sceneName.getWindow().sizeToScene();
It works when downsizing and upsizing from my own testing.
Here's some example code so you can better understand what I did:
public void start(Stage stage) throws IOException {
// Height of 300, width of 300
Parent scene1 = FXMLLoader.load(getClass().getResource("scene1.fxml"));
// Height of 400, width of 400
Parent scene2 = FXMLLoader.load(getClass().getResource("scene2.fxml"));
// Starting off in the smaller scene
Scene mainScene = new Scene(scene1); // Scene & Window are 300x300
stage.setScene(mainScene);
stage.show();
// Switching to the larger scene resource, that doesn't fit in the window
mainScene.setRoot(scene2); // Scene is 400x400 but can only see 300x300
// Resizing the window so the larger scene fits
mainScene.getWindow().sizeToScene(); // Window is now 400x400 & everything is visible
}
I hope this helps someone.
Source:
https://docs.oracle.com/javase/8/javafx/api/javafx/stage/Window.html#sizeToScene--

Monotouch - make UIView scrollable

I have a view with 4 text boxes and and a logo at the top - when the user is entering information the text pad covers up some of these controls, how can I make the view scroll so that this isn't an issue.
I have tried adding the view to a UIScrollView but that doesn't seem to do anything?
I've included a snippit below of how I've handled your situation. If I'm understanding you correctly, you do not wish to have a scrollable view, rather you want to the view to move in conjunction with switching to and from fields to alleviate and visual hindrances caused by the keyboard.
Goodluck!
private void ScrollTheView(bool movedUp, float scrollamount, UIView ViewToMove)
{
//To invoke a views built-in animation behaviour,
//you create an animation block and
//set the duration of the move...
//Set the display scroll animation and duration...
UIView.BeginAnimations(string.Empty, System.IntPtr.Zero);
UIView.SetAnimationDuration(0.15);
//Get Display size...
RectangleF frame = ViewToMove.Frame;
if (movedUp) {
//If the view should be moved up,
//subtract the keyboard height from the display...
frame.Y -= scrollamount;
}
else {
//If the view shouldn't be moved up, restore it
//by adding the keyboard height back to the original...
frame.Y += scrollamount;
}
//Assign the new frame to the view...
ViewToMove.Frame = frame;
//Tell the view that your all done with setting
//the animation parameters, and it should
//start the animation...
UIView.CommitAnimations();
}
You need to set more to the UIScrollView than just put subviews in it. Set up the ContentSize property properly for the complete size of the subviews so the scrollview knows about the larger content in it, than you can control the scrolling position, zoom factor and so on.
There are plenty of samples on iOS SDK, just check the UIScrollView documentation, transformation to Monotouch from ObjectiveC is straightforward or check blog post at http://blog.touch4apps.com/home/iphone-monotouch-development/monotouch-infinite-loop-image-scroll-view where I have a sample with images autoscrolled in UIScrollView.
something like this.
textBox.EditingDidBegin += delegate {
var offset = scrollView.contentOffset;
offset.Y -= 200;
scrollView.contentOffset = offset;
}

Resources