I have an array of bitmap images loaded using harism curl page library found on https://github.com/harism/android_page_curl . I need to integrate zoom with gestures on each bitmap image. how can i achieve zoom with gestures. can anyone help me its a core issue i am facing for days.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lp = this;
util = new Utils();
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(index);
// mCurlView.setBackgroundResource(R.drawable.icon);
imHome = (ImageView)findViewById(R.id.imHome);
imHome.setClickable(true);
imHome.setOnClickListener(lp);
btOne=(Button)findViewById(R.id.btOne);
btTwo=(Button)findViewById(R.id.btTwo);
btThree=(Button)findViewById(R.id.btThree);
btFour=(Button)findViewById(R.id.btFour);
llPageOne = (LinearLayout)findViewById(R.id.llPageOne);
btOne.setOnClickListener(this);
btTwo.setOnClickListener(this);
btThree.setOnClickListener(this);
btFour.setOnClickListener(this);
// This is something somewhat experimental. Before uncommenting next
// line, please see method comments in CurlView.
// mCurlView.setEnableTouchPressure(true);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = {
R.drawable.luxury,R.drawable.luxury1,R.drawable.luxury_two
};
#Override
public int getPageCount() {
//return 5;
int pagesCount = 0;
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int wwidth = displaymetrics.widthPixels;
int hheight = displaymetrics.heightPixels;
if(wwidth > hheight){
if((mBitmapIds.length % 2) > 0)
pagesCount = (mBitmapIds.length / 2) + 1;
else
pagesCount = mBitmapIds.length / 2;
}else{
pagesCount = mBitmapIds.length;
}
System.out.println("page count "+pagesCount);
return pagesCount;
}
private Bitmap loadBitmap(int width, int height, int index) {
Bitmap b = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
b.eraseColor(0xFFFFFFFF);
Canvas c = new Canvas(b);
Drawable d = getResources().getDrawable(mBitmapIds[index]);
System.out.println("canvas width: "+c.getWidth());
int margin = 3;//7
int border = 3;//2
Rect r = new Rect(margin, margin, width - margin, height - margin);
int imageWidth = r.width() - (border * 2);
int imageHeight = imageWidth * d.getIntrinsicHeight()
/ d.getIntrinsicWidth();
if (imageHeight > r.height() - (border * 2)) {
imageHeight = r.height() - (border * 2);
imageWidth = imageHeight * d.getIntrinsicWidth()
/ d.getIntrinsicHeight();
}
Log.d("TAG", String.valueOf(imageHeight));
if (lp.getWindow().getWindowManager().getDefaultDisplay()
.getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
// portrait mode
r.left += ((r.width() - imageWidth) / 2) - border;
r.right = r.left + imageWidth + border + border;
} else if (lp.getWindow().getWindowManager().getDefaultDisplay()
.getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
// landscape
r.left += ((r.width() - imageWidth)) - border-122;
r.right = r.left + imageWidth + border + border+122;
}
r.top += ((r.height() - imageHeight) / 2) - border;
r.bottom = r.top + imageHeight + border + border;
Paint p = new Paint();
p.setColor(0xFFC0C0C0);
c.drawRect(r, p);
r.left += border;
r.right -= border;
r.top += border;
r.bottom -= border;
d.setBounds(r);
d.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int wwidth = displaymetrics.widthPixels;
int hheight = displaymetrics.heightPixels;
if(wwidth > hheight){
System.out.println("index "+(index*2));
System.out.println("index2 "+(index*2)+1);
System.out.println("case landscape orientation...");
if (index >0){
front = loadBitmap(width, height, (index*2));
back = loadBitmap(width, height, (index*2)+1);
}else {
front = loadBitmap(width, height, (index));
back = loadBitmap(width, height, (index));
}
System.out.println( "MyActivity.onCreate debug message "+String.valueOf(index));
Matrix matrix = new Matrix();
matrix.preScale(-1.0f, 1.0f);
Bitmap mirroredBitmap = Bitmap.createBitmap(back, 0, 0, back.getWidth(), back.getHeight(), matrix, false);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(mirroredBitmap, CurlPage.SIDE_BACK);
// if (mCurlView.getCurrentIndex()==0){
//
// showPage1();
//
// }else {
//
// hidePage1();
// }
System.out.println("mCurlView.getCurrentIndex() "+mCurlView.getCurrentIndex());
}else{
System.out.println("case portrait orientation...");
Bitmap front = loadBitmap(width, height, index);
Bitmap back = loadBitmap(width, height, index);
System.out.println( "MyActivity.onCreate debug message "+String.valueOf(index));
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
}
}
}
/**
* CurlView size changed observer.
*/
private class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.000f, .000f, .000f, .000f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
mCurlView.setMargins(.005f, .005f, .00f, .00f);
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btOne:
util.sendUri(this, "http://google.com/");
break;
case R.id.btTwo:
util.sendUri(this, "http://google.com/");
break;
case R.id.btThree:
util.sendUri(this, "http://google.com/");
break;
case R.id.btFour:
util.sendUri(this, "http://google.com/");
break;
case R.id.imHome:
mCurlView.setCurrentIndex(0);
System.out.println("home pressed");
mCurlView.onResume();
break;
}
}
public void showPage1(){
llPageOne.setVisibility(View.VISIBLE);
}
public void hidePage1(){
llPageOne.setVisibility(View.GONE);
}
// #Override
// public void onBackPressed() {
// // TODO Auto-generated method stub
//
// startActivity (new Intent (this,MyActivityMenuActivity.class));
// }
//
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drop_list, menu);
return super.onCreateOptionsMenu(menu);
}
/**
* Override function onOptionsItemSelected(MenuItem item)
* Identify the item
* Call super class's onOptionsItemSelected(MenuItem item)
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.menu_option_one){
startActivity (new Intent (this,ContactForm.class));
}
return super.onOptionsItemSelected(item);
}
Override onTouchEvent(MotionEvent event) and create an instance of ScaleGestureDetector.OnScaleGestureListener to detect zoom event. Than draw your bitmap according to zoom ratio
Related
I am new to android and I want to blur image on finger touch.
I have searched some example but I found like based on seek bar value whole image get blurred.
But I want something like I can set radius of finger touch and then based on that touch, that portion of image get blurred.
MYANSWER
MainActivity1.java
here,MainActivity.java file contains bitmap that is passed from MainActivity.java .
public class MainActivity1 extends Activity implements OnClickListener {
// button
private ImageButton opacityBtn;
// custom view
private DrawingView drawView;
private Object bmpimg;
private ImageButton currPaint;
Bitmap b;
private int originalheight;
private int originalwidth;
public Bitmap tem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
Intent i1 = getIntent();
String img = i1.getStringExtra("imgpath");
Log.e("img", "" + img);
b = BitmapFactory.decodeFile(img);
// get button
opacityBtn = (ImageButton) findViewById(R.id.opacity_btn);
// listen
opacityBtn.setOnClickListener(this);
// custom view instance
// LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
// currPaint = (ImageButton)paintLayout.getChildAt(0);
// currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
Log.e("mainactivity1", "" + b);
// bmpimg = Bitmap.createScaledBitmap(srcimg, 100, 50, true);
// Display display = getWindowManager().getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// int width = size.x;
// int height = size.y;
// tem=Bitmap.createScaledBitmap(b, width,
// height - 200, true);
drawView = (DrawingView) findViewById(R.id.drawing);
// fetching height and width of device
int widthPx = getWindowManager().getDefaultDisplay().getWidth();
int heightPx = getWindowManager().getDefaultDisplay().getHeight();
// set new height and width to custom class drawing view
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) drawView
.getLayoutParams();
if (b.getHeight() < heightPx && b.getWidth() < widthPx) {
params.height = b.getHeight();
params.width = b.getWidth();
} else {
if (b.getHeight() > heightPx && b.getWidth() > widthPx) {
params.height = heightPx;
params.width = widthPx;
} else if (b.getWidth() > widthPx) {
params.width = widthPx;
params.height = b.getHeight();
} else {
params.width = b.getWidth();
params.height = heightPx;
}
}
drawView.setLayoutParams(params);
drawView.setCanvasBitmap(b, b.getHeight(),
b.getWidth(), widthPx, heightPx);
if(b.getHeight()<heightPx&&b.getWidth()<widthPx){
this.originalheight=b.getHeight();
this.originalwidth=b.getWidth();
}else{
if(b.getHeight()>heightPx&&b.getWidth()>widthPx){
this.originalheight=heightPx;
this.originalwidth=widthPx;
}
else if(b.getWidth()>widthPx){
this.originalwidth=widthPx;
this.originalheight=b.getHeight();
}
else{
this.originalwidth=b.getWidth();
this.originalheight=heightPx;
}
}
tem=Bitmap.createScaledBitmap(b, originalwidth,
originalheight, true);
Bitmap bitmap=createBitmap_ScriptIntrinsicBlur(tem,40);
drawView.firstsetupdrawing(bitmap);
// drawView.setScree_w(width);
// drawView.setScreen_h(height);
}
/*
* #Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the
* menu; this adds items to the action bar if it is present.
* getMenuInflater().inflate(R.menu.main, menu); return true; }
*/
/* public void paintClicked(View view) {
//use chosen color
//set erase false
// drawView.setErase(false);
// drawView.setPaintAlpha(100);
// drawView.setBrushSize(drawView.getLastBrushSize());
if(view!=currPaint){
Bitmap bitmap=createBitmap_ScriptIntrinsicBlur(tem,40);
drawView.firstsetupdrawing(bitmap);
// ImageButton imgView = (ImageButton)view;
// String color = view.getTag().toString();
// drawView.setColor(color);
// //update ui
// imgView.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
// currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint));
// currPaint=(ImageButton)view;
}
}
*/
#Override
public void onClick(View view) {
if (view.getId() == R.id.opacity_btn) {
// launch opacity chooser
final Dialog seekDialog = new Dialog(this);
seekDialog.setTitle("Opacity level:");
seekDialog.setContentView(R.layout.opacity_chooser);
// get ui elements
final TextView seekTxt = (TextView) seekDialog
.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar) seekDialog
.findViewById(R.id.opacity_seek);
// set max
seekOpq.setMax(40);
// show current level
int currLevel = drawView.getPaintAlpha();
seekTxt.setText(currLevel + "%");
seekOpq.setProgress(currLevel);
// update as user interacts
seekOpq.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekTxt.setText(Integer.toString(progress) + "%");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// listen for clicks on ok
Button opqBtn = (Button) seekDialog.findViewById(R.id.opq_ok);
opqBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap=createBitmap_ScriptIntrinsicBlur(tem, seekOpq.getProgress());
drawView.setPaintAlpha(seekOpq.getProgress(),bitmap);
seekDialog.dismiss();
}
});
// show dialog
seekDialog.show();
}
}
public Bitmap createBitmap_ScriptIntrinsicBlur(Bitmap src, int radius) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
// Radius range (0 < r <= 25)
/* if (r <= 1) {
r = 1;
} else if (r > 25) {
r = 25;
}
Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(this);
Allocation blurInput = Allocation.createFromBitmap(renderScript, src);
Allocation blurOutput = Allocation.createFromBitmap(renderScript,
bitmap);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
blur.setInput(blurInput);
blur.setRadius(r);
blur.forEach(blurOutput);
blurOutput.copyTo(bitmap);
renderScript.destroy();
return bitmap;*/
//here i can make radius up to 40 use for it below code
int w = src.getWidth();
int h = src.getHeight();
int[] pix = new int[w * h];
src.getPixels(pix, 0, w, 0, 0, w, h);
for(int r = radius; r >= 1; r /= 2)
{
for(int i = r; i < h - r; i++)
{
for(int j = r; j < w - r; j++)
{
int tl = pix[(i - r) * w + j - r];
int tr = pix[(i - r) * w + j + r];
int tc = pix[(i - r) * w + j];
int bl = pix[(i + r) * w + j - r];
int br = pix[(i + r) * w + j + r];
int bc = pix[(i + r) * w + j];
int cl = pix[i * w + j - r];
int cr = pix[i * w + j + r];
pix[(i * w) + j] = 0xFF000000 |
(((tl & 0xFF) + (tr & 0xFF) + (tc & 0xFF) + (bl & 0xFF) +
(br & 0xFF) + (bc & 0xFF) + (cl & 0xFF) + (cr & 0xFF)) >> 3) & 0xFF |
(((tl & 0xFF00) + (tr & 0xFF00) + (tc & 0xFF00) + (bl & 0xFF00)
+ (br & 0xFF00) + (bc & 0xFF00) + (cl & 0xFF00) + (cr & 0xFF00)) >> 3) & 0xFF00 |
(((tl & 0xFF0000) + (tr & 0xFF0000) + (tc & 0xFF0000) +
(bl & 0xFF0000) + (br & 0xFF0000) + (bc & 0xFF0000) + (cl & 0xFF0000) +
(cr & 0xFF0000)) >> 3) & 0xFF0000;
}
}
}
Bitmap blurred = Bitmap.createBitmap(w, h, src.getConfig());
blurred.setPixels(pix, 0, w, 0, 0, w, h);
return blurred;
}
}
DrawingView.java
Here,DrawingView.java contains canavas so we canput image on canvas and blur it.
public class DrawingView extends View {
// drawing path
private Path drawPath;
// drawing and canvas paint
private Paint drawPaint, canvasPaint;
// initial color
private int paintColor = 0xFFC0C0C0, paintAlpha = 255;
// canvas
private Canvas drawCanvas;
// canvas bitmap
private Bitmap canvasBitmap;
int originalheight,originalwidth;
/**
* #return the scree_w
*/
private BlurMaskFilter blurMaskFilter;
public int scree_w, screen_h;
public void setCanvasBitmap(Bitmap bitmap1, int i, int j, int widthPx, int heightPx) {
this.canvasBitmap = bitmap1;
if(i<heightPx&&j<widthPx){
this.originalheight=i;
this.originalwidth=j;
}else{
if(i>heightPx&&j>widthPx){
this.originalheight=heightPx-1;
this.originalwidth=widthPx-1;
}
else if(j>widthPx){
this.originalwidth=widthPx-1;
this.originalheight=i;
}
else{
this.originalwidth=j;
this.originalheight=heightPx-1;
}
}
}
public void setScree_w(int width) {
// TODO Auto-generated method stub
this.scree_w = width;
}
public void setScreen_h(int height) {
// TODO Auto-generated method stub
this.screen_h = height;
}
// constructor
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
setupDrawing();
}
// prepare drawing
private void setupDrawing() {
drawPath = new Path();
drawPaint = new Paint();
//
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(30);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint();
// BitmapShader patternBMPshader = new BitmapShader(canvasBitmap,
// Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
// //color and shader
// drawPaint.setColor(0xFFFFFFFF);
// drawPaint.setShader(patternBMPshader);
blurMaskFilter = new BlurMaskFilter( 5,
BlurMaskFilter.Blur.NORMAL);
drawPaint.setMaskFilter(blurMaskFilter);
}
public void firstsetupdrawing( Bitmap bitmap){
drawPath = new Path();
drawPaint = new Paint();
//
// drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(30);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
canvasPaint = new Paint();
// BitmapShader patternBMPshader = new BitmapShader(canvasBitmap,
// Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
// //color and shader
// drawPaint.setColor(0xFFFFFFFF);
// drawPaint.setShader(patternBMPshader);
blurMaskFilter = new BlurMaskFilter( 5,
BlurMaskFilter.Blur.NORMAL);
drawPaint.setMaskFilter(blurMaskFilter);
drawPaint.setColor(paintColor);
// drawPaint.setAlpha(paintAlpha);
BitmapShader patternBMPshader = new BitmapShader(bitmap,
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
//color and shader
drawPaint.setColor(0xFFFFFFFF);
drawPaint.setShader(patternBMPshader);
}
// view assigned size
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// int i=canvasBitmap.getHeight();
// int y=canvasBitmap.getWidth();
Log.e("hiyt wid-------------------------", "" + scree_w
+ "dsgvdfg sunita u will be happy" + screen_h);
canvasBitmap = Bitmap.createScaledBitmap(canvasBitmap,originalwidth+1,originalheight+1, true);
drawCanvas = new Canvas(canvasBitmap);
}
// draw view
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
// respond to touch interaction
float x = 0, y = 0;
public boolean onTouchEvent(MotionEvent event) {
Log.e("getalph drawing view", "" + getPaintAlpha());
float touchX = 0, touchY = 0;
x = touchX;
y = touchY;
touchX = event.getX();
touchY = event.getY();
// respond to down, move and up events
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
/*
* if (x == touchX && y == touchY) {
*
* drawPath.moveTo(touchX + 1, touchY + 1); } else {
*/
drawPath.moveTo(touchX, touchY);
// }
break;
case MotionEvent.ACTION_MOVE:
/*
* if (x == touchX && y == touchY) {
*
* drawPath.lineTo(touchX + 1, touchY + 1);
*
* } else {
*/
drawPath.lineTo(touchX, touchY);
// }
break;
case MotionEvent.ACTION_UP:
/*
* if (x == touchX && y == touchY) {
*
* drawPath.lineTo(touchX + 1, touchY + 1);
* drawCanvas.drawPath(drawPath, drawPaint); drawPath.reset(); }
*
* else {
*/
drawPath.lineTo(touchX, touchY);
drawCanvas.drawPath(drawPath, drawPaint);
drawPath.reset();
// }
break;
default:
return false;
}
// redraw
invalidate();
return true;
}
// return current alpha
public int getPaintAlpha() {
return Math.round((float) paintAlpha / 255 * 40);
}
// set alpha
public void setPaintAlpha(int newAlpha, Bitmap bitmap) {
paintAlpha = Math.round((float) newAlpha / 40 * 255);
drawPaint.setColor(paintColor);
drawPaint.setAlpha(paintAlpha);
BitmapShader patternBMPshader = new BitmapShader(bitmap,
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
//color and shader
drawPaint.setColor(0xFFFFFFFF);
drawPaint.setShader(patternBMPshader);
}
public void setColor(String newColor) {
invalidate();
//check whether color value or pattern name
if(newColor.startsWith("#")){
paintColor = Color.parseColor(newColor);
drawPaint.setColor(paintColor);
drawPaint.setShader(null);
}
else{
//pattern
int patternID = getResources().getIdentifier(
newColor, "drawable", "com.example.drawingfun");
//decode
// Bitmap patternBMP = BitmapFactory.decodeResource(getResources(), patternID);
Bitmap patternBMP = BitmapFactory.decodeResource(getResources(),R.drawable.sun);
//create shader
Log.e("drawing view pattern+getalpha", "" + patternBMP+"dsfsdsd"+getPaintAlpha());
BitmapShader patternBMPshader = new BitmapShader(patternBMP,
Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
//color and shader
drawPaint.setColor(0xFFFFFFFF);
drawPaint.setShader(patternBMPshader);
}
}
}
I am using set as wallpaper in my android app. But when I set image as wallpaper its zoom upto some extent on device. I want when I set image as wallpaper. This fit on every screen device. I am using DisplayMetrices but its not working perfect.
Code-
public class FullImageActivity extends Activity {
int position, width, height;
LinearLayout full;
Button btn;
Context context;
DisplayMetrics metrics;
public Integer[] mThumbId = {
R.drawable.kri1, R.drawable.kri2,
R.drawable.kri3, R.drawable.kri4,
R.drawable.kri5, R.drawable.kri6,
R.drawable.kri7, R.drawable.kri8,
R.drawable.kri9
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
// get intent data
Intent i = getIntent();
// Selected image id
position = i.getExtras().getInt("id");
full = (LinearLayout) findViewById(R.id.full);
btn = (Button)findViewById(R.id.btn);
changeBackground();
metrics = this.getResources().getDisplayMetrics();
width = metrics.widthPixels;
height = metrics.heightPixels;
btn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.suggestDesiredDimensions(width, height);
myWallpaperManager.setResource(mThumbId[position]);
} catch (IOException e) {
e.printStackTrace();
}
}});
ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
full.setOnTouchListener(activitySwipeDetector);
}
private void changeBackground(){
full.setBackgroundResource(mThumbId[position]);
}
public class ActivitySwipeDetector implements View.OnTouchListener {
static final String logTag = "ActivitySwipeDetector";
static final int MIN_DISTANCE = 100;
private float downX, upX;
Activity activity;
public ActivitySwipeDetector(Activity activity){
this.activity = activity;
}
public void onRightToLeftSwipe(){
Log.i(logTag, "RightToLeftSwipe!");
if(position < mThumbId.length - 1){
position++;
changeBackground();
}
}
public void onLeftToRightSwipe(){
Log.i(logTag, "LeftToRightSwipe!");
if(position > 0){
position--;
changeBackground();
}
}
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
return true;
}
case MotionEvent.ACTION_UP: {
upX = event.getX();
float deltaX = downX - upX;
// swipe horizontal?
if(Math.abs(deltaX) > MIN_DISTANCE){
// left or right
if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
}
else {
Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
return false; // We don't consume the event
}
return true;
}
}
return false;
}
}
}
Thanks in Advance.
Try this-
Bitmap bmap = BitmapFactory.decodeStream(getResources().openRawResource(mThumb[position]));
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
Bitmap yourbitmap = Bitmap.createScaledBitmap(bmap, width, height, true);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
try {
wallpaperManager.setBitmap(yourbitmap);
} catch (IOException e) {
e.printStackTrace();
}
i'm using this library in my app
it works and it's easy
CropImage
it's open source so you can edit the library as you like
have fun
I guess you need a Image Scaling Algorithm that maintains the image Aspect Ratio,
Store the best image you have in your drawable folder and let this Algorithm scale down the best image to fit the device's Height & Width, maintaining the aspect ratio of the orignal Image.
Bitmap scaleDownLargeImageWithAspectRatio(Bitmap image)
{
int imaheVerticalAspectRatio,imageHorizontalAspectRatio;
float bestFitScalingFactor=0;
float percesionValue=(float) 0.2;
//getAspect Ratio of Image
int imageHeight=(int) (Math.ceil((double) image.getHeight()/100)*100);
int imageWidth=(int) (Math.ceil((double) image.getWidth()/100)*100);
int GCD=BigInteger.valueOf(imageHeight).gcd(BigInteger.valueOf(imageWidth)).intValue();
imaheVerticalAspectRatio=imageHeight/GCD;
imageHorizontalAspectRatio=imageWidth/GCD;
Log.i("scaleDownLargeImageWIthAspectRatio","Image Dimensions(W:H): "+imageWidth+":"+imageHeight);
Log.i("scaleDownLargeImageWIthAspectRatio","Image AspectRatio(W:H): "+imageHorizontalAspectRatio+":"+imaheVerticalAspectRatio);
//getContainer Dimensions
int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
int displayHeight = getWindowManager().getDefaultDisplay().getHeight();
//I wanted to show the image to fit the entire device, as a best case. So my ccontainer dimensions were displayWidth & displayHeight. For your case, you will need to fetch container dimensions at run time or you can pass static values to these two parameters
int leftMargin = 0;
int rightMargin = 0;
int topMargin = 0;
int bottomMargin = 0;
int containerWidth = displayWidth - (leftMargin + rightMargin);
int containerHeight = displayHeight - (topMargin + bottomMargin);
Log.i("scaleDownLargeImageWIthAspectRatio","Container dimensions(W:H): "+containerWidth+":"+containerHeight);
//iterate to get bestFitScaleFactor per constraints
while((imageHorizontalAspectRatio*bestFitScalingFactor <= containerWidth) &&
(imaheVerticalAspectRatio*bestFitScalingFactor<= containerHeight))
{
bestFitScalingFactor+=percesionValue;
}
//return bestFit bitmap
int bestFitHeight=(int) (imaheVerticalAspectRatio*bestFitScalingFactor);
int bestFitWidth=(int) (imageHorizontalAspectRatio*bestFitScalingFactor);
Log.i("scaleDownLargeImageWIthAspectRatio","bestFitScalingFactor: "+bestFitScalingFactor);
Log.i("scaleDownLargeImageWIthAspectRatio","bestFitOutPutDimesions(W:H): "+bestFitWidth+":"+bestFitHeight);
image=Bitmap.createScaledBitmap(image, bestFitWidth,bestFitHeight, true);
//Position the bitmap centre of the container
int leftPadding=(containerWidth-image.getWidth())/2;
int topPadding=(containerHeight-image.getHeight())/2;
Bitmap backDrop=Bitmap.createBitmap(containerWidth, containerHeight, Bitmap.Config.RGB_565);
Canvas can = new Canvas(backDrop);
can.drawBitmap(image, leftPadding, topPadding, null);
return backDrop;
}
private void changeBackground()
{
Drawable inputDrawable = mThumbId[position];
Bitmap bitmap = ((BitmapDrawable)inputDrawable).getBitmap();
bitmap = scaleDownLargeImageWithAspectRatio(bitmap);
#SuppressWarnings("deprecation")
Drawable outDrawable=new BitmapDrawable(bitmap);
full.setBackground(outDrawable);
}
try this code to set image as Wallpaper
public void setWallpaper(final Bitmap bitmp)
{
int screenWidth=getWallpaperDesiredMinimumWidth();
int screenHeight=getWallpaperDesiredMinimumHeight();
try {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Bitmap btm = getResizedBitmap(bitmp, screenHeight, screenWidth);
wallpaperManager.setBitmap(btm);
Toast toast=Toast.makeText(this, "Done", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 0);
toast.show();
} catch (IOException e) {
e.printStackTrace();
}
}
and
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
/**
* create a matrix for the manipulation
*/
Matrix matrix = new Matrix();
/**
* resize the bit map
*/
matrix.postScale(scaleWidth, scaleHeight);
/**
* recreate the new Bitmap
*/
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
EDIT :
You are required to just call the that function with desired bitmap
btn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
setWallpaper(BitmapFactory.decodeResource(FullImageActivity.this.getResources(),
mThumbId[position]));
}});
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
I'm new in Android Programming I'm Trying to make slideshow animated live wallpaper and all ok but the problem is when I set the wallpaper the scale of image is stretched to screen I want it to scale to all the phone screens and when swipe the wallpaper get the right part of image I Want Advice about this problem.
my code is :
public class CustomWallpaper extends WallpaperService {
#Override
public Engine onCreateEngine() {
return new WallpaperEngine();
}
class WallpaperEngine extends Engine {
//Duration between slides in milliseconds
private final int SLIDE_DURATION = 8;
private int[] mImagesArray;
private int mImagesArrayIndex = 0;
private Thread mDrawWallpaper;
private String mImageScale = "Fit to screen";
private CustomWallpaperHelper customWallpaperHelper;
public WallpaperEngine() {
customWallpaperHelper = new CustomWallpaperHelper(getApplicationContext(), getResources());
mImagesArray = new int[] {R.drawable.image_1,R.drawable.image_2,R.drawable.image_3,R.drawable.image_4,R.drawable.image_5,R.drawable.image_6,R.drawable.image_7,R.drawable.image_8,R.drawable.image_9,R.drawable.image_10,R.drawable.image_11,R.drawable.image_12,R.drawable.image_13,R.drawable.image_14,R.drawable.image_15,R.drawable.image_16,R.drawable.image_17,R.drawable.image_18,R.drawable.image_19,R.drawable.image_20,R.drawable.image_21,R.drawable.image_22,R.drawable.image_23,R.drawable.image_24,R.drawable.image_25,R.drawable.image_26,R.drawable.image_27,R.drawable.image_28,R.drawable.image_29,R.drawable.image_30,R.drawable.image_31,R.drawable.image_32,R.drawable.image_33,R.drawable.image_34,R.drawable.image_35,R.drawable.image_36,R.drawable.image_37,R.drawable.image_38,R.drawable.image_39,R.drawable.image_40,R.drawable.image_41};
mDrawWallpaper = new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
drawFrame();
incrementCounter();
Thread.sleep(SLIDE_DURATION);
}
} catch (Exception e) {
//
}
}
});
mDrawWallpaper.start();
}
private void incrementCounter() {
mImagesArrayIndex++;
if (mImagesArrayIndex >= mImagesArray.length) {
mImagesArrayIndex = 0;
}
}
private void drawFrame() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
drawImage(canvas);
}
} finally {
if (canvas != null) {
holder.unlockCanvasAndPost(canvas);
}
}
}
private void drawImage(Canvas canvas) {
//Get the image and resize it
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
//Draw background
customWallpaperHelper.setBackground(canvas);
//Scale the canvas
PointF mScale = customWallpaperHelper.getCanvasScale(mImageScale, image.getWidth(), image.getHeight());
canvas.scale(mScale.x, mScale.y);
//Draw the image on screen
Point mPos = customWallpaperHelper.getImagePos(mScale, image.getWidth(), image.getHeight());
canvas.drawBitmap(image, mPos.x, mPos.y, null);
}
}
}
and the other class is:
public class CustomWallpaperHelper {
public final static String IMAGE_SCALE_STRETCH_TO_SCREEN = "Stretch to screen";
public final static String IMAGE_SCALE_FIT_TO_SCREEN = "Fit to screen";
private Context mContext;
private Resources mResources;
private Point screenSize = new Point();
private Bitmap bgImageScaled;
private Point bgImagePos = new Point(0, 0);
public CustomWallpaperHelper(Context mContext, Resources mResources) {
this.mContext = mContext;
this.mResources = mResources;
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
screenSize.x = display.getWidth();
screenSize.y = display.getHeight();
;
}
private void scaleBackground() {
String imageScale = "Stretch to screen";
Bitmap bgImage = null;
if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
bgImagePos = new Point(0, 0);
bgImageScaled = Bitmap.createScaledBitmap(bgImage, screenSize.x, screenSize.y, true);
}
}
public void setBackground(Canvas canvas) {
if (bgImageScaled != null) {
canvas.drawBitmap(bgImageScaled, bgImagePos.x, bgImagePos.y, null);
} else {
canvas.drawColor(0xff000000);
}
}
public int getScreenWidth() {
return screenSize.x;
}
public int getScreenHeight() {
return screenSize.y;
}
public Point getImagePos(PointF canvasScale, int imageWidth, int imageHeight) {
Point imagePos = new Point();
imagePos.x = (int) (screenSize.x - (imageWidth * canvasScale.x)) / 2;
imagePos.y = (int) (screenSize.y - (imageHeight * canvasScale.y)) / 2;
return imagePos;
}
public PointF getCanvasScale(String imageScale, int imageWidth, int imageHeight) {
PointF canvasScale = new PointF(1f, 1f);
if (imageScale.equals(IMAGE_SCALE_STRETCH_TO_SCREEN)) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = getScreenHeight() / (1f * imageHeight);
} else {
boolean tooWide = false;
boolean tooTall = false;
if (getScreenWidth() < imageWidth) {
tooWide = true;
}
if (getScreenHeight() < imageHeight) {
tooTall = true;
}
if (tooWide && tooTall) {
int x = imageWidth / getScreenWidth();
int y = imageHeight / getScreenHeight();
if (x > y) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = 1;
} else {
canvasScale.x = 1;
canvasScale.y = getScreenHeight() / (1f * imageHeight);
}
} else if (tooWide) {
canvasScale.x = getScreenWidth() / (1f * imageWidth);
canvasScale.y = 1;
} else if (tooTall) {
canvasScale.x = 1;
canvasScale.y = getScreenHeight() / (1f * imageHeight);
}
}
return canvasScale;
}
}
I want Advice for this problem.
Thanks.
no need to do anything just Replace your below method with my code.
private void drawImage(Canvas canvas)
{
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray[mImagesArrayIndex]);
Bitmap b=Bitmap.createScaledBitmap(image, canvas.getWidth(), canvas.getHeight(), true);
canvas.drawBitmap(b, 0,0, null);
}
I would suggest that you crop the images instead of resizing them. Something like:
Rect r = new Rect(left, top, right, bottom);
Bitmap croppedImage = null;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1){
InputStream in = mContentResolver.openInputStream(mSaveUri);
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(in, false);
croppedImage = decoder.decodeRegion(r, null);
} else {
final int width = r.width();
final int height = r.height();
croppedImage = Bitmap.createBitmap(mBitmap, r.left, r.top, width, height);
croppedImage.setDensity(croppedImage.getDensity() * mOutputX / width);
}
return croppedImage;
Hope this helps...
I want to set onClickListener for each page in the flip view below. How can i achieve this in the CurlActivity class below
public class CurlActivity extends Activity {
private CurlView mCurlView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(index);
mCurlView.setBackgroundColor(0xFF202830);
System.out.println("index : "+index);
// This is something somewhat experimental. Before uncommenting next
// line, please see method comments in CurlView.
// mCurlView.setEnableTouchPressure(true);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
private int[] mBitmapIds = { R.drawable.obama, R.drawable.page_one,R.drawable.road_rage,
R.drawable.pavp_page_one, R.drawable.world };
#Override
public int getPageCount() {
return 6;
}
private Bitmap loadBitmap(int width, int height, int index) {
Bitmap b = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
b.eraseColor(0xFFFFFFFF);
Canvas c = new Canvas(b);
Drawable d = getResources().getDrawable(mBitmapIds[index]);
int margin = 7;
int border = 3;
Rect r = new Rect(margin, margin, width - margin, height - margin);
int imageWidth = r.width() - (border * 2);
int imageHeight = imageWidth * d.getIntrinsicHeight()
/ d.getIntrinsicWidth();
if (imageHeight > r.height() - (border * 2)) {
imageHeight = r.height() - (border * 2);
imageWidth = imageHeight * d.getIntrinsicWidth()
/ d.getIntrinsicHeight();
}
r.left += ((r.width() - imageWidth) / 2) - border;
r.right = r.left + imageWidth + border + border;
r.top += ((r.height() - imageHeight) / 2) - border;
r.bottom = r.top + imageHeight + border + border;
Paint p = new Paint();
p.setColor(0xFFC0C0C0);
c.drawRect(r, p);
r.left += border;
r.right -= border;
r.top += border;
r.bottom -= border;
d.setBounds(r);
d.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
switch (index) {
// First case is image on front side, solid colored back.
case 0: {
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
break;
}
// Second case is image on back side, solid colored front.
case 1: {
Bitmap back = loadBitmap(width, height, 2);
page.setTexture(back, CurlPage.SIDE_BACK);
page.setColor(Color.rgb(127, 140, 180), CurlPage.SIDE_FRONT);
break;
}
// Third case is images on both sides.
case 2: {
Bitmap front = loadBitmap(width, height, 1);
Bitmap back = loadBitmap(width, height, 3);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
break;
}
// Fourth case is images on both sides - plus they are blend against
// separate colors.
case 3: {
Bitmap front = loadBitmap(width, height, 2);
Bitmap back = loadBitmap(width, height, 1);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
page.setColor(Color.argb(127, 170, 130, 255),
CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(255, 190, 150), CurlPage.SIDE_BACK);
break;
}
// Fifth case is same image is assigned to front and back. In this
// scenario only one texture is used and shared for both sides.
case 4:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_BOTH);
page.setColor(Color.argb(127, 255, 255, 255),
CurlPage.SIDE_BACK);
break;
}
}
}
/**
* CurlView size changed observer.
*/
private class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
mCurlView.setMargins(.0f, .0f, .0f, .0f);
}
}
}
}
So, I am using https://github.com/harism/android_page_curl , this project to achieve the curl functionality to create a book. But I want to achieve the same while streaming images from web directly, obviously in an asynchronous manner.
But then I would require an OpenGL , progress bar for the same. But I don't have any knowledge in OPENGL, So how can I go about tweaking this code and achieve the functionality I want.
Also , have a look at this question for more clear view of what I want to achieve...
PageCurl(magazine) with Image from web
package fi.harism.curl;
public class CurlActivity extends Activity {
private CurlView mCurlView;
Button btn;
private AQuery aq;
Drawable d =null;
TextView mText;
List<String> data;
MediaPlayer mPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(index);
mCurlView.setBackgroundColor(Color.GREEN);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
private String[] mBitmapStrings={"http://myserver.com/image/img%20p1.png",
"http://myserver.com/image/img%20p2.png",
"http://myserver.com/image/img%20p3.png",
"http://myserver.com/image/img%20p4.png"};
#Override
public int getPageCount() {
return mBitmapStrings.length;
}
private Bitmap loadBitmap(int width, int height, int index) throws MalformedURLException, IOException {
Bitmap b = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
b.eraseColor(0xFFFFFFFF);
Canvas c = new Canvas(b);
if(index==mBitmapStrings.length)
{
index=0;
}
Drawable d = new BitmapDrawable(drawable_from_url(mBitmapStrings[index]));
int margin = 7;
int border = 3;
Rect r = new Rect(margin, margin, width - margin, height - margin);
int imageWidth = r.width() - (border * 2);
int imageHeight = imageWidth * d.getIntrinsicHeight()
/ d.getIntrinsicWidth();
if (imageHeight > r.height() - (border * 2)) {
imageHeight = r.height() - (border * 2);
imageWidth = imageHeight * d.getIntrinsicWidth()
/ d.getIntrinsicHeight();
}
r.left += ((r.width() - imageWidth) / 2) - border;
r.right = r.left + imageWidth + border + border;
r.top += ((r.height() - imageHeight) / 2) - border;
r.bottom = r.top + imageHeight + border + border;
Paint p = new Paint();
p.setColor(0xFFC0C0C0);
c.drawRect(r, p);
r.left += border;
r.right -= border;
r.top += border;
r.bottom -= border;
d.setBounds(r);
d.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
Bitmap front;
try {
front = loadBitmap(width, height, index);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* CurlView size changed observer.
*/
private class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
/*if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {*/
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
//mCurlView.setMargins(.1f, .1f, .1f, .1f);
mCurlView.setMargins(0,0,0,0);
//}
}
}
Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return x;
}
}
----Edit----
Also , I am using android-query library for asynchronous image/file
loading. Would it be feasible to use it with this project in case of
streaming images from web. How?
public class CurlActivity extends Activity {
private CurlView mCurlView;
Bitmap y;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int index = 0;
if (getLastNonConfigurationInstance() != null) {
index = (Integer) getLastNonConfigurationInstance();
}
mCurlView = (CurlView) findViewById(R.id.curl);
mCurlView.setPageProvider(new PageProvider());
mCurlView.setSizeChangedObserver(new SizeChangedObserver());
mCurlView.setCurrentIndex(index);
mCurlView.setBackgroundColor(0xFF202830);
}
#Override
public void onPause() {
super.onPause();
mCurlView.onPause();
}
#Override
public void onResume() {
super.onResume();
mCurlView.onResume();
}
#Override
public Object onRetainNonConfigurationInstance() {
return mCurlView.getCurrentIndex();
}
/**
* Bitmap provider.
*/
private class PageProvider implements CurlView.PageProvider {
// Bitmap resources.
/*private int[] mBitmapIds = { R.drawable.obama, R.drawable.road_rage,
R.drawable.taipei_101, R.drawable.world };*/
private String[] mBitmapIds = {"your url","your url",
"your urlg", "your url" }; //your image url
#Override
public int getPageCount() {
return 5;
}
private Bitmap loadBitmap(int width, int height, int index) {
Bitmap b = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
b.eraseColor(0xFFFFFFFF);
Canvas c = new Canvas(b);
//Uri url = Uri.parse("http://stackoverflow.com");
//Drawable d =getResources().getDrawable(url);
//Drawable d = getResources().getDrawable(mBitmapIds[index]);
try {
drawableFromUrl(mBitmapIds[index]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = new BitmapDrawable(getResources(),y);
//Drawable d = new BitmapDrawable(drawable_from_url(y));
int margin = 7;
int border = 3;
Rect r = new Rect(margin, margin, width - margin, height - margin);
int imageWidth = r.width() - (border * 2);
int imageHeight = imageWidth * d.getIntrinsicHeight()
/ d.getIntrinsicWidth();
if (imageHeight > r.height() - (border * 2)) {
imageHeight = r.height() - (border * 2);
imageWidth = imageHeight * d.getIntrinsicWidth()
/ d.getIntrinsicHeight();
}
r.left += ((r.width() - imageWidth) / 2) - border;
r.right = r.left + imageWidth + border + border;
r.top += ((r.height() - imageHeight) / 2) - border;
r.bottom = r.top + imageHeight + border + border;
Paint p = new Paint();
p.setColor(0xFFC0C0C0);
c.drawRect(r, p);
r.left += border;
r.right -= border;
r.top += border;
r.bottom -= border;
d.setBounds(r);
d.draw(c);
return b;
}
#Override
public void updatePage(CurlPage page, int width, int height, int index) {
switch (index) {
// First case is image on front side, solid colored back.
case 0: {
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(180, 180, 180), CurlPage.SIDE_BACK);
break;
}
// Second case is image on back side, solid colored front.
case 1: {
Bitmap back = loadBitmap(width, height, 2);
page.setTexture(back, CurlPage.SIDE_BACK);
page.setColor(Color.rgb(127, 140, 180), CurlPage.SIDE_FRONT);
break;
}
// Third case is images on both sides.
case 2: {
Bitmap front = loadBitmap(width, height, 1);
Bitmap back = loadBitmap(width, height, 3);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
break;
}
// Fourth case is images on both sides - plus they are blend against
// separate colors.
case 3: {
Bitmap front = loadBitmap(width, height, 2);
Bitmap back = loadBitmap(width, height, 1);
page.setTexture(front, CurlPage.SIDE_FRONT);
page.setTexture(back, CurlPage.SIDE_BACK);
page.setColor(Color.argb(127, 170, 130, 255),
CurlPage.SIDE_FRONT);
page.setColor(Color.rgb(255, 190, 150), CurlPage.SIDE_BACK);
break;
}
// Fifth case is same image is assigned to front and back. In this
// scenario only one texture is used and shared for both sides.
case 4:
Bitmap front = loadBitmap(width, height, 0);
page.setTexture(front, CurlPage.SIDE_BOTH);
page.setColor(Color.argb(127, 255, 255, 255),
CurlPage.SIDE_BACK);
break;
}
}
}
/**
* CurlView size changed observer.
*/
private class SizeChangedObserver implements CurlView.SizeChangedObserver {
#Override
public void onSizeChanged(int w, int h) {
if (w > h) {
mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
mCurlView.setMargins(.1f, .05f, .1f, .05f);
} else {
mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
mCurlView.setMargins(.1f, .1f, .1f, .1f);
}
}
}
public void drawableFromUrl(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
y = BitmapFactory.decodeStream(input);
}
}