Create imageView programmatically in Watch Kit - imageview

i'm trying to create an image view for a watch app, i'm trying to create programmatically but the code used in a classic view controller doesn't work.
let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
view.addSubview(imageView)
how i can do the same thing for watch kit?
thanks

You can't dynamically create views in WatchKit. You need to create your entire interface in a storyboard. You can have elements of your storyboard hidden and then programmatically unhide them.
In your storyboard you can use WKInterfaceImage to hold the image. You can set the image at runtime using setImage:.

With SwiftUI, you can add a new image view to your view by using the ForEach and Image components.
struct ContentView: View {
#State var images = [UIImage]()
var body: some View {
VStack {
ForEach(images, id: \.self) { image in
Image(uiImage: image)
}
Button("Add Image") {
images.append(.init(imageLiteralResourceName: "image-name"))
}
}
}
}

Related

HOWTO: Manipulate Back Arrow Icon and Button on Navigation Bar (Xamarin Forms / Android)

I am attempting to change the size of the back arrow in the navigation bar.
Using information from this article, I have added the following code:
protected override Task<bool> OnPushAsync(Page view, bool animated)
{
var result = base.OnPushAsync(view, animated);
var activity = (Activity) Context;
var toolbar = activity.FindViewById<Toolbar>(Resource.Id.toolbar);
if (toolbar != null)
{
if (toolbar.NavigationIcon != null)
{
if (toolbar.NavigationIcon is DrawerArrowDrawable navigationIcon)
{
// Code goes here?
}
}
}
return result;
}
If this is indeed the correct path, what code goes in the area marked by the comment "Code goes here?"?
* UPDATE *
I realized that what I am trying to figure out was not exactly described in my original question.
More specifically, when I mentioned that I am trying to resize the navigation bar back arrow, what I am really trying to do is to resize the button that the icon appears on.
For example, if I shrink the height of the navigation bar using code like the following:
On<Android>().SetBarHeight(100);
The button that the icon appears on will be clipped.
Ultimately, what I am trying to accomplish is resizing the icon AND the button that the icon appears on. I have already figured out how to do the former.
I am attempting to change the size of the back arrow in the navigation bar.
If you want to change size of the back button in the navigation bar, you can get new icon from Drawable in resource for toolbar.NavigationIcon.
public class NavigationPageRenderer : Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer
{
public AppCompToolbar toolbar;
public Activity context;
protected override Task<bool> OnPushAsync(Page view, bool animated)
{
var retVal = base.OnPushAsync(view, animated);
context = (Activity)Forms.Context;
toolbar = context.FindViewById<AppCompToolbar>(Droid.Resource.Id.toolbar);
if (toolbar != null)
{
if (toolbar.NavigationIcon != null)
{
if (toolbar.NavigationIcon is DrawerArrowDrawable navigationIcon)
{
// Code goes here?
toolbar.NavigationIcon = Android.Support.V7.Content.Res.AppCompatResources.GetDrawable(context, Resource.Drawable.back);
toolbar.Title = "Back";
}
}
}
return retVal;
}
}
Here is the sample you can take a look:
https://github.com/hachi1030-Allen/XamarinCustomNavBar
<NavigationPage.TitleView> will help you out there. This is a XAML approach.
Example:
<NavigationPage.TitleView>
<StackLayout>
....
</StackLayout>
</NavigationPage.TitleView>
Using this approach you will be able to set HeightRequest and WidthRequest of whatever element you place inside the StackLayout and whatever else you want to amend.
Also, note that if you are having icon size problems it may be worth looking into whether or not your drawable/ icons are the right size for the right resolution.

Xamarin.Forms - Show Embedded Resource image in listview Template

I have a list view in Xamarin.Forms and I have set ItemTemplate e.g.
listView.ItemTemplate = new DataTemplate(() =>
{
Image img = new Image();
img.SetBinding(Image.SourceProperty, "ImageUrl");
...so on
}
This works if image is stored in the same project but I have moved image to PCL project and set to "Embedded Resource".
I need to state somehting like below but it doesn't work, how can I achieve this so it will bind "embedded resource" to image control in list item.
img.SetBinding(Image.SourceProperty, "ImageSource.FromResource(ImageUrl)");
Thanks
Specify the assembly that the image exists
ImageSource.FromResource("yourNamespace.imageName.png", typeof(className).GetTypeInfo().Assembly))
Created readonly property in model to return ImageSource and it still uses ImageUrl property to return ImageSource and now I just bind to this new readonly property.
//in model
[JsonIgnore]
public ImageSource ImageUrlSource { get { return ImageSource.FromResource(ImageUrl); } }
listView.ItemTemplate = new DataTemplate(() =>
{
Image img = new Image();
img.SetBinding(Image.SourceProperty, "ImageUrlSource");
...so on
}

xamarin binding a button in code to viewModel (without xaml)

I'm using the mvvm approach to develop a barcode scanning app with xamarin. The main hurdle was that the 3rd party scanner object does not work in xaml. I used a ContentPage to create a simple logic-less c# code view which allows me to have a footer with buttons and a logo overlayed at the bottom of the scanner. My problem is that could not find any great best practices for binding items from your code view to your viewModel, as opposed binding a xaml view to a viewModel. Here is some of my view below.
public class BarcodeScannerPage : ContentPage
{
ZXingScannerView zxing;
BarcodeViewModel viewModel;
public BarcodeScannerPage() : base()
{
try
{
viewModel = new BarcodeViewModel();
BindingContext = viewModel;
zxing = new ZXingScannerView
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Options = new MobileBarcodeScanningOptions
{
TryHarder = true,
DelayBetweenContinuousScans = 3000
},
ScanResultCommand = viewModel.GetResult
};
var cancelButton = new Button
{
BackgroundColor = Color.Gray,
Text = "Cancel",
TextColor = Color.Blue,
FontSize = 15,
Command = viewModel.CancelButton
};
Binding cancelBinding = new Binding
{
Source = viewModel.CancelIsAvailable,
//Path = "ShowCancel",
Mode = BindingMode.OneWay,
};
cancelButton.SetBinding(IsVisibleProperty, cancelBinding);
var doneButton = new Button
{
BackgroundColor = Color.Gray,
Text = "Done",
TextColor = Color.Blue,
FontSize = 15,
Command = viewModel.DoneButton
};
Binding doneBinding = new Binding
{
Source = viewModel.DoneIsAvailable,
//Path = "ShowDone",
Mode = BindingMode.OneWay,
};
doneButton.SetBinding(Button.IsVisibleProperty, doneBinding);
When a barcode is scanned my command, GetResultCommand, sends the result to my BarcodeView model. I have created two Bools in my BarcodeView model named isDoneAvailable and isCancelAvailable. I want to bind these values to the Visibility property of the doneButton and cancelButton in my view. Right now the buttons are bound to whatever the bool values are at the creation of BarcodeViewModel, but they DO NOT update. I need to be able to control visibility from the GetResultCommand method of my BarcodeViewModel. Specifically, when a certain number of barcodes are scanned, I want to make the buttons appear and disappear. I have a feeling they don't update because the path is not set, but when I uncomment the path, the binding doesn't work at all. Any ideas what I've done wrong with the bindings of the buttons, or the correct way to set the Path to my bools in the viewModel? Here is some of my BarcodeViewModel code below.
public class BarcodeViewModel : INotifyPropertyChanged
{
public bool CancelIsAvailable { get { return _cancelIsAvailable; } set { _cancelIsAvailable = value; OnPropertyChanged("ShowCancel"); } }
public bool DoneIsAvailable { get { return _doneIsAvailable; } set { _doneIsAvailable = value; OnPropertyChanged("ShowDone"); } }
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
I still would like to know the correct way to get this binding to update but, I was able to work-around this issue by creating a button in my viewModel and referencing it in my view. Then when I dynamically updated the button in my viewModel, it also updated in my view.

How to drag a copy of an Item through Drag and DropArea mechanism in QML?

Hello,
I'm using Qt 5.2.1 for Android on windows
I've gone through the different drag and drop examples provided with Qt, but non of them address my problem, although I found This Example copy Text via drag and drop, but I want to copy a whole Item.
Note: I don't want external copy, just inside the application.
Thank you
Am a noop, this is just an idea,
Create a new Object ( same as your dragged Item )
Copy the Dragged item properties into the newly created object
Destroy the source
lets say you have and Item:
// DraggedItem.qml
import QtQuick 2.0
Item {
id:draggedItem
property string itemText
property string imageSource
Image {
id: img
source: imageSource
}
Text {
id: txt
text: qsTr("text")
}
}
Then you can have your drop area like this:
import QtQuick 2.0
Item {
id:dropItem
DropArea {
id: dropArea
anchors.fill: parent
onDropped: {
if (drop.source.parent !== draggedItem) {
// Create new Item
var newItem = createNewItem();
// Copy the source item properties into the new one
newItem.width = parent.width;
newItem.height = drop.source.height;
newItem.itemText = drop.source.itemText
newItem.imageSource = drop.source.imageSource
// destroy the source
drop.source.destroy();
}
}
}
function createNewItem() {
var component = Qt.createComponent("DraggedItem.qml");
if (component.status === Component.Ready)
{
var newItem = component.createObject(parent, {"x":0,
"y":0});
if (newItem === null)
console.log("Error creating new Item");
}
return newItem
}
}
This code is not tested. There should be a better way to do this

Change mouse cursor to a bitmap (Flex 4)?

In Flex 4, how can I change the cursor to a Bitmap image determined at runtime? All the examples I've seen use CursorManager.setCursor to set the cursor to a class specified at compile time.
What I want to do is change the cursor to a bitmap whose bitmapData is determined by the context.
package cursor
{
import flash.display.BitmapData;
import flash.display.PixelSnapping;
import mx.core.BitmapAsset;
public class RuntimeBitmap1 extends BitmapAsset
{
public static var staticBitmapData:BitmapData;
public function RuntimeBitmap1()
{
super(staticBitmapData);
}
}
}
Usage:
var bitmapData:BitmapData = new BitmapData(50, 50, false, 0x88888888);
RuntimeBitmap1.staticBitmapData = bitmapData;
cursorManager.setCursor(RuntimeBitmap1, 0);
I wanted to draw a UIComponent as a cursor.
I managed it using a combination of Maxims answer and this Flex Cookbox article. The only change I had to make to Maxim answer was a s follows:
public function RuntimeBitmap1()
{
super(RuntimeBitmap1.staticBitmapData);
}
Otherwise staticBitmapData came through as null in the constructor.
Here are a few simple steps to change the default cursor with a bitmap image:
Create your cursor of type Bitmap by using an image of your choice. You can also set the bitmapData dynamically during runtime.
var DEFAULT_CURSOR_IMAGE : Class;
var myCursorBitmap : Bitmap;
...
myCursorBitmap = new DEFAULT_CURSOR_IMAGE();
Register to receive mouse move events and update cursor position accordingly.
function onMouseMove(event : MouseEvent) : void
{
myCursorBitmap.x = event.localX;
myCursorBitmap.y = event.localY;
}
Hide the real cursor by using Mouse.hide().
Show your custom cursor. You may update cursor shape later by setting bitmapData dynamically.
addChild(myCursorBitmap);
...
myCursorBitmap.bitmapData = myNewCursor;
To restore the default cursor, remove your cursor bitmap from the stage and call Mouse.show().

Resources