JavaFX with Google Maps - Outstanding resource locks detected: D3D Vram Pool: - resources

I'm writing a program that displays Google Map in JavaFX application. Below is a code:
public class Window {
private static JFXPanel fxContainer;
MyBrowser myBrowser;
double lat;
double lon;
WindowGPSServer windowsgpsserver;
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Window().init();
}
});
}
public void init() {
fxContainer = new JFXPanel();
windowsgpsserver = new WindowGPSServer(fxContainer);
windowsgpsserver.setVisible(true);
// create JavaFX scene
Platform.runLater(new Runnable() {
#Override
public void run() {
//javaFX operations should go here
createScene();
}
});
}
private void createScene() {
myBrowser = new MyBrowser();
myBrowser.setCache(false);
Scene scene = new Scene(myBrowser);
fxContainer.setScene(scene);
this.windowsgpsserver.setMyBrowser(myBrowser);
}
}
and:
public class MyBrowser extends Pane {
double lat;
double lon;
MyBrowser myBrowser;
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
public MyBrowser() {
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) (tk.getScreenSize().getWidth()));
int ySize = ((int) tk.getScreenSize().getHeight());
xSize= new Double(xSize*0.75).intValue();
ySize= new Double(ySize*0.90).intValue();
webView.setPrefSize(xSize, ySize);
final URL urlGoogleMaps = getClass().getResource("demo.html");
webEngine.load(urlGoogleMaps.toExternalForm());
webEngine.setOnAlert(new EventHandler<WebEvent<String>>() {
#Override
public void handle(WebEvent<String> e) {
System.out.println(e.toString());
System.out.println(e.getData());
System.gc();
}
});
getChildren().add(webView);
}
public void ChangeLocation(String latit, String longi) {
lat = Double.parseDouble(latit);
lon = Double.parseDouble(longi);
webEngine.executeScript("" +
"window.lat = " + lat + ";" +
"window.lon = " + lon + ";" +
"document.goToLocation(window.lat, window.lon);"
);
}
}
and demo.html file:
<body style="height: 100%;" onload="mapaStart()">
<script type="text/javascript">
var map;
function mapaStart() {
//document.map = new google.maps.Map(document.getElementById("mapcanvas"));
var latlng = new google.maps.LatLng(35.857908, 10.598997);
var Options = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcanvas"), Options);
//var carMarkerImage = new google.maps.MarkerImage('resources/images/car.png');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(35.857908, 10.598997),
map: map,
draggable: false,
//icon: carMarkerImage,
title: "",
autoPan: true
});
var infobulle = new google.maps.InfoWindow({
content: "Aktualna pozycja"
});
google.maps.event.addListener(marker, 'mouseover', function() {
infobulle.open(map, marker);
});
document.goToLocation = function(x, y) {
alert("goToLocation, x: " + x +", y:" + y);
var latLng = new google.maps.LatLng(x, y);
marker.setPosition(latLng);
map.setCenter(latLng);
}
google.maps.event.addListener(map, 'zoom_changed', function() {
alert("ZOOM");
var MapOptions = {
scrollwheel: false
};
map.setOptions(MapOptions)
setTimeout(aaa, 1000);
});
}
function aaa() {
var MapOptions = {
scrollwheel: true
};
map.setOptions(MapOptions)
}
</script>
<div id="mapcanvas" style="width: 100%; height: 90%; border: 1px solid black; background: gray;">
</div>
</body>
</html>
fxContainer is added to JPanel and displayed in Swing application.
After starting program everything works just fine. But after zooming in and out a couple of times, program becomes unresponsive (hards to zoom, move map to sides) and following error is displayed:
"Outstanding resource locks detected:
D3D Vram Pool: 268 433 488 used (100,0%), 268 433 488 managed (100,0%), 268 435 456 total
39 total resources being managed
average resource age is 0.1 frames
0 resources at maximum supported age (0,000000)
35 resources marked permanent (89,700000)
2 resources have had mismatched locks (5,100000)
2 resources locked (5,100000)
35 resources contain interesting data (89,700000)
0 resources disappeared (0,000000)"
Can anybody help me to solve this problem?
Thank you
Martin

It is a known issue. Could you upvote this https://javafx-jira.kenai.com/browse/RT-36649.
Thanks ! :)

Related

RecylerView to pdf

Hello am new to Android studio
I have made recylerview for transaction details . I need to create pdf for this recylerview items.
Example: I have 24 cardviews in recylerview so need to create pdf with each page 4 cardviews only . So totally I need to get pdf as 6 pages .
How to do that . Thanks in advance.
This is sample image of my view
Am passing below code
recyclerView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(),View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
Bitmap bm=Bitmap.createBitmap(recyclerView.getWidth(),recyclerView.getMeasuredHeight(),Bitmap.Config.ARGB_8888);
String mpath2="/mnt/sdcard/mathanpaymentpdf";
File imageFile = new File(mpath2);
PDFHelper pdfHelper = new PDFHelper(imageFile,this);
pdfHelper.saveImageToPDF(recyclerView,bm,"mathan"+System.currentTimeMillis());
public class PDFHelper {
private File mFolder;
private File mFile;
private Context mContext;
public PDFHelper(File folder, Context context) {
this.mContext = context;
this.mFolder = folder;
if(!mFolder.exists())
mFolder.mkdirs();
}
public void saveImageToPDF(View title, Bitmap bitmap, String filename) {
mFile = new File(mFolder, filename + ".pdf");
if (!mFile.exists()) {
int height = title.getHeight() + bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, title.getHeight(), bitmap.getWidth(),bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This am tried am getting pdf on a single page only
Just I need to split into multiple pages.
Note: I need code in java, not in kotlin
Am solved this by using itext library
implementation 'com.itextpdf:itextpdf:5.0.6'
Then call with RecylerView
public void generatePDF(RecyclerView view) {
RecyclerView.Adapter adapter = view.getAdapter();
int sie2=adapter.getItemCount();
if (sie2 == 0) {
Toast.makeText(this,"No Transactions",Toast.LENGTH_LONG).show();
}else{
Bitmap bigBitmap = null;
if (adapter != null) {
int size = adapter.getItemCount();
int height = 0;
Paint paint = new Paint();
int iHeight = 0;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
for (int i = 0; i < size; i++) {
RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
adapter.onBindViewHolder(holder, i);
holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
holder.itemView.setDrawingCacheEnabled(true);
holder.itemView.buildDrawingCache();
Bitmap drawingCache = holder.itemView.getDrawingCache();
if (drawingCache != null) {
bitmaCache.put(String.valueOf(i), drawingCache);
}
height += holder.itemView.getMeasuredHeight();
}
bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
Canvas bigCanvas = new Canvas(bigBitmap);
bigCanvas.drawColor(Color.WHITE);
Document document=new Document();
final File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MAT"+System.currentTimeMillis()+".pdf");
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < size; i++) {
try {
//Adding the content to the document
Bitmap bmp = bitmaCache.get(String.valueOf(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
com.itextpdf.text.Image image= com.itextpdf.text.Image.getInstance(stream.toByteArray());
//Image image = Image.getInstance(stream.toByteArray());
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 50) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER | com.itextpdf.text.Image.ALIGN_TOP);
if (!document.isOpen()) {
document.open();
}
document.add(image);
} catch (Exception ex) {
Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
}
}
if (document.isOpen()) {
document.close();
}
// Set on UI Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivityAdminMain.this);
builder.setTitle("Success")
.setMessage("PDF File Generated Successfully.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// dialog.dismiss();
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent56 = Intent.createChooser(target, "Open File");
try {
startActivity(intent56);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivityAdminMain.this,"No PDF Viewer Installed.",Toast.LENGTH_LONG).show();
}
}
}).show();
}
});
}}
}
100% working.. This helps to anyone needs

How to animate a filled triangle (drawn by a path) in Android Studio

I'm trying to build a jigsaw-like app for Android that involves the user moving polygonal pieces around the screen by touch event.
I can draw - for example - a triangle, and fill it. I can also move it smoothly round the screen but it leaves a trace - so that the screen rapidly fills up :-(
So I am wondering how to adjust the onDraw method so that the previous positions of the triangle are not included. Or is there some other technique? The question has been asked once before but did not get a satisfactory answer. I am quite new to Android work so I am sure a kind expert will be able to point me in the right direction!
The view:
public class GameView extends View {
public Triangle T1;
Paint paint = new Paint();
private Path path;
public GameView(Context context) {
super(context);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.GREEN);
initTriangle();
}
public void initTriangle() {
int T1Points[][] = new int[3][2];
T1Points[0][0] = -200;
T1Points[0][1] = -100;
T1Points[1][0] = 200;
T1Points[1][1] = -100;
T1Points[2][0] = 0;
T1Points[2][1] = 100;
float[] position = new float[2];
position[0] = (float) 200.0;
position[1] = (float) 100.0;
T1 = new Triangle("T1", T1Points, position);
path = T1.getPath();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float[] pos = new float[2];
pos[0] = event.getX(); //nextx;
pos[1] = event.getY(); //nexty;
T1.setPosition(pos );
Path path = new Path();
path = T1.getPath();
postInvalidate();
return true;
}
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
}
Triangle class:
public class Triangle {
public int[][] myPoints;
public Path path;
public String myname;
public float[] position;
public Triangle (String name, int[][] newpoints, float[] posn) {
myPoints = new int[4][2];
int i;
for (i = 0; i < 3; i++) {
myPoints[i][0] = newpoints[i][0];
myPoints[i][1] = newpoints[i][1];
}
myPoints[3][0] = newpoints[0][0]; // closed circuit for future needs
myPoints[3][1] = newpoints[0][1];
path = new Path();
position = new float[2];
position[0] = posn[0];
position[1] = posn[1];
myname = name;
updatePath();
}
public void setPosition(float[] newPosition){
position[0] = newPosition[0];
position[1] = newPosition[1];
updatePath();
}
public void updatePath(){
int startx = myPoints[0][0] + Math.round(position[0]);
int starty = myPoints[0][1] + Math.round(position[1]);
path.moveTo(startx,starty);
for (int i = 1; i < myPoints.length; i++)
{
int newx = myPoints[i][0] + Math.round(position[0]);
int newy = myPoints[i][1] + Math.round(position[1]);
path.lineTo(newx,newy);
}
path.close();
}
public Path getPath() {
return path;
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uk.mydomain.animatedtriangle.GameView gameView = new uk.mydomain.animatedtriangle.GameView(this);
RelativeLayout relativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
relativeLayout.setLayoutParams(relativeParams);
setContentView(relativeLayout);
relativeLayout.addView(gameView);
}
Sorted! Just needed to add a path.reset() at the end of onDraw.

Radio Button in Xamarin.iOS listen for tap?

I need to get a view with two radio buttons working, where only one can be clicked at a time. Using the answer posted here by user Alanc Liu: Radio button in xamarin.ios I've got my View Controller looking correct, but I can't figure out how to listen for the tap to set the other radio button to false.
I've tried playing around with adding a gesture recognizer to the ViewDidLoad method, but haven't gotten anything to work yet (I've mostly just used the storyboard previously to add methods to button clicks).
My View Controller:
public partial class VerifyViewController : UIViewController
{
public VerifyViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
MyRadioButton tBtn = new MyRadioButton(new CGPoint(100, 300), "TEXT PHONE");
MyRadioButton eBtn = new MyRadioButton(new CGPoint(100, 375), "EMAIL");
this.Add(tBtn);
this.Add(eBtn);
}
}
And his Radio Button Classes:
public class MyRadioButton : UIView
{
private CircleView circleView;
private UILabel lbTitle;
public bool State {
get {
return circleView.State;
}
set {
circleView.State = value;
}
}
public MyRadioButton (CGPoint pt,string title)
{
this.Frame = new CGRect (pt, new CGSize (150, 30));
circleView = new CircleView (new CGRect(0, 0, 30, 30));
lbTitle = new UILabel (new CGRect (30, 0, 120, 30));
lbTitle.Text = title;
lbTitle.TextAlignment = UITextAlignment.Center;
this.AddSubview (circleView);
this.AddSubview (lbTitle);
this.BackgroundColor = UIColor.FromRGBA(1,0,0,0.3f);
UITapGestureRecognizer tapGR = new UITapGestureRecognizer (() => {
State = !State;
});
this.AddGestureRecognizer (tapGR);
}
}
class CircleView : UIView
{
private bool state = false;
public bool State {
get {
return state;
}
set {
state = value;
this.SetNeedsDisplay ();
}
}
public CircleView (CGRect frame)
{
this.BackgroundColor = UIColor.Clear;
this.Frame = frame;
}
public override void Draw (CoreGraphics.CGRect rect)
{
CGContext con = UIGraphics.GetCurrentContext ();
float padding = 5;
con.AddEllipseInRect (new CGRect (padding, padding, rect.Width - 2 * padding, rect.Height - 2 * padding));
con.StrokePath ();
if (state) {
float insidePadding = 8;
con.AddEllipseInRect (new CGRect (insidePadding, insidePadding, rect.Width - 2 * insidePadding, rect.Height - 2 * insidePadding));
con.FillPath ();
}
}
}
Expose a public event in MyRadioButton ,call it when we tap the radio button.
Code in MyRadioButton:
//define the event inside MyRadioButton
public delegate void TapHandler(MyRadioButton sender);
public event TapHandler Tap;
//call it in MyRadioButton(CGPoint pt, string title)
UITapGestureRecognizer tapGR = new UITapGestureRecognizer(() => {
State = !State;
Tap(this);
});
Handle the event inside your viewController
Code in ViewController
MyRadioButton tBtn = new MyRadioButton(new CGPoint(100, 300), "TEXT PHONE");
MyRadioButton eBtn = new MyRadioButton(new CGPoint(100, 375), "EMAIL");
this.Add(tBtn);
this.Add(eBtn);
tBtn.Tap += Btn_Tap;
eBtn.Tap += Btn_Tap;
// set the default selection
Btn_Tap(tBtn);
MyRadioButton PreviousButton;
private void Btn_Tap(MyRadioButton sender)
{
if(PreviousButton != null)
{
//set previous to false
PreviousButton.State = false;
}
//set current to true
sender.State = true;
//assign current to previous
PreviousButton = sender;
}
Result:

MvvmCross bind to progress indicator in MvxDialogViewController

I have a MvxDialogViewController and I'm trying to use the progress indicator shown in the Xamarin example by adding bindable properties.
I can get the indicator to appear when I set Visble to true programatically but not when I bind to a vm property.
Here is the view code:
var bindings = this.CreateInlineBindingTarget<LoginViewModel>();
Root = new RootElement("Login")
{
new Section("Login Credentials")
{
new EntryElement("Username", "Enter user name").Bind(bindings, vm => vm.UserName),
new EntryElement("Password", "Enter password", "", true).Bind(bindings, vm => vm.Password)
}
};
_bindableProgress = new BindableProgress(UIScreen.MainScreen.Bounds).Bind(bindings, b => b.Visible, vm => vm.IsBusy);
_bindableProgress.Title = "Logging in...";
View.Add(_bindableProgress);
I also tried to bind like this:
var set = this.CreateBindingSet<LoginView, LoginViewModel>();
set.Bind(_bindableProgress).For(b => b.Title).To(vm => vm.ProgressTitle);
set.Bind(_bindableProgress).For(b => b.Visible).To(vm => vm.IsBusy);
set.Apply();
But neither way worked.
Here is by BindableProgress class:
public class BindableProgress : UIView
{
private UIActivityIndicatorView _activitySpinner;
private UILabel _loadingLabel;
public string Title { get; set; }
private bool _visible;
public bool Visible
{
get { return _visible; }
set
{
_visible = value;
if (_visible)
{
Show();
}
else
{
Hide();
}
}
}
public BindableProgress(RectangleF frame) : base(frame)
{
// configurable bits
BackgroundColor = UIColor.Black;
Alpha = 0;
AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
float labelHeight = 22;
float labelWidth = Frame.Width - 20;
// derive the center x and y
float centerX = Frame.Width/2;
float centerY = Frame.Height/2;
// create the activity spinner, center it horizontally and put it 5 points above center x
_activitySpinner = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge);
_activitySpinner.Frame = new RectangleF(
centerX - (_activitySpinner.Frame.Width / 2),
centerY - _activitySpinner.Frame.Height - 20,
_activitySpinner.Frame.Width,
_activitySpinner.Frame.Height);
_activitySpinner.AutoresizingMask = UIViewAutoresizing.FlexibleMargins;
AddSubview(_activitySpinner);
// create and configure the label
_loadingLabel = new UILabel(new RectangleF(
centerX - (labelWidth/2),
centerY + 20,
labelWidth,
labelHeight
));
_loadingLabel.BackgroundColor = UIColor.Clear;
_loadingLabel.TextColor = UIColor.White;
_loadingLabel.TextAlignment = UITextAlignment.Center;
_loadingLabel.AutoresizingMask = UIViewAutoresizing.FlexibleMargins;
AddSubview(_loadingLabel);
}
private void Show()
{
_loadingLabel.Text = Title;
Alpha = 0.75f;
_activitySpinner.StartAnimating();
}
/// <summary>
/// Fades out the control and then removes it from the super view
/// </summary>
private void Hide()
{
_activitySpinner.StopAnimating();
Animate(
0.5, // duration
() => { Alpha = 0; },
() => { RemoveFromSuperview(); }
);
}
}
Any ideas?
UPDATE
My vm property looks like this
private bool _isBusy;
public bool IsBusy
{
get { return _isBusy; }
set { _isBusy = value; RaisePropertyChanged(() => IsBusy); }
}
It works fine in Android so I'm guessing the problem in not with that.
IsBusy is probably false at binding time. So _visible is set to false and Hide() is called. Now the view is removed from the superview and you can't show it anymore, because Show() doesn't add it to the superview again. Try to omit the RemoveFromSuperview();. Or modify the Visible property like this:
public bool Visible
{
get { return _visible; }
set
{
if(_visible == value)
return;
_visible = value;
if (_visible)
{
Show();
}
else
{
Hide();
}
}
}

How to load a widget as a different thread in gtk? (vala)

I created this class, And I want to load thumbnails into the iconview as a different thread for efficiency reasons, because the gui load very slow if I do it in the same thread. But when I create the thread, it doesn't works, it draw some thumbnails and then they dissapear. When I use join, it works. This is my code:
public class FotoThumbnailPane : Gtk.ScrolledWindow{
private FotoThumbnailPane_i pane;
private string namet;
public FotoThumbnailPane(string name){
this.namet = name;
}
public void set_imagelist(fileutils.ImageList image_list){
pane = new FotoThumbnailPane_i(image_list);
this.add (pane);
this.set_min_content_width(140);
this.show_all();
}
//This is my threaded function
public void* load_thumbs(){
pane.set_visible(false);
pane.newmodel = new Gtk.ListStore (2, typeof (Gdk.Pixbuf), typeof (string));
pane.set_selection_mode (Gtk.SelectionMode.SINGLE);
pane.set_pixbuf_column (0);
pane.set_model(pane.newmodel);
string icon_style = """
.thumbnail-view {
background-color: #FFFFFF;
}
.thumbnail-view:selected {
background-color: #9D9D9D;
border-color: shade (mix (rgb (34, 255, 120), #fff, 0.5), 0.9);
}
""";
var icon_view_style = new Gtk.CssProvider ();
try {
icon_view_style.load_from_data (icon_style, -1);
} catch (Error e) {
warning (e.message);
}
pane.get_style_context ().add_class ("thumbnail-view");
pane.get_style_context ().add_provider (icon_view_style, Gtk.STYLE_PROVIDER_PRIORITY_THEME);
//Add thumbnails to the iconview
string buff;
for(int i=1; i<pane.image_list.size; i++){
buff = pane.image_list.get_full_filename(i);
stdout.printf("Added %s to thumbnail\n", buff);
var image = new Gdk.Pixbuf.from_file_at_scale(buff, 110, 80, false);
// Add the wallpaper name and thumbnail to the IconView
Gtk.TreeIter root;
pane.newmodel.append(out root);
pane.newmodel.set(root, 0, image, -1);
pane.newmodel.set(root, 1, pane.image_list.get_filename(i), -1);
// Select the thumbnail if it is the first in list
if (i==0) {
pane.select_path (pane.newmodel.get_path (root));
}
pane.iters.append (root);
}
pane.set_sensitive(true);
this.queue_draw();
return null;
}
}
You don't actually need to deal with threads in your program--you can just use an asynchronous method to load the content. Specifically, Gdk.Pixbuf.new_from_stream_at_scale_async.
Here is an example:
public async void load (Gtk.Image img, string filename) {
GLib.File file = GLib.File.new_for_commandline_arg (filename);
try {
GLib.InputStream stream = yield file.read_async ();
Gdk.Pixbuf pixbuf = yield Gdk.Pixbuf.new_from_stream_at_scale_async (stream, 320, -1, true);
img.set_from_pixbuf (pixbuf);
} catch ( GLib.Error e ) {
GLib.error (e.message);
}
}
private static int main (string[] args) {
GLib.return_val_if_fail (args.length > 1, -1);
Gtk.init (ref args);
Gtk.Window win = new Gtk.Window ();
win.destroy.connect (() => {
Gtk.main_quit ();
});
Gtk.Image image = new Gtk.Image ();
win.add (image);
load.begin (image, args[1], (obj, async_res) => {
GLib.debug ("Finished loading.");
});
win.show_all ();
Gtk.main ();
return 0;
}

Resources