How to add a Marker/Pin on an ImageView Android? - java

I would like to ask on how to implement or add a marker on an imageView.
I rendered an SVG using svglib and used a customImageView so that I can zoom and pan around the image.
here is my code on how i used my customImageView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SVG svg;
switch (mNum) {
case 1:
svg = SVGParser.getSVGFromResource(getResources(), R.raw.t1);
break;
case 2:
svg = SVGParser.getSVGFromResource(getResources(), R.raw.t2);
break;
case 3:
svg = SVGParser.getSVGFromResource(getResources(), R.raw.t3);
break;
case 4:
svg = SVGParser.getSVGFromResource(getResources(), R.raw.t4);
break;
default:
svg = SVGParser.getSVGFromResource(getResources(),
R.raw.android);
}
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
imageView = (GestureImageView) v.findViewById(R.id.imageView1);
imageView.setStrict(false);
imageView.setStartingScale(lastScale);
// if(lastXPosition!=0 && lastYPosition!=0)
imageView.setStartingPosition(lastXPosition, lastYPosition);
// Log.i("tag",
// "lastXPosition" + lastXPosition);
// Log.i("tag",
// "lastYPosition" + lastYPosition);
// Log.i("tag",
// "lastScale" + lastScale);
// imageView.setRotation(45);
// imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
if (Build.VERSION.SDK_INT > 15)
imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
imageView.setImageDrawable(svg.createPictureDrawable());
((TextView) tv).setText("Floor number: " + mNum);
imageView.setBackgroundColor(Color.WHITE);
// tv.setBackgroundDrawable(getResources().getDrawable(
// android.R.drawable.gallery_thumb));
// imageView.setScaleType(ScaleType.CENTER);
// ((GestureImageView)imageView).setScale(x);
return v;
}
Now I would like to add a pin just like the image below...
(source: modality.com)
But my problem is that when I pan around the marker I added is not bonded with the image SVG thus left behind at a certain position when panning...
Here's my code...
NOTE: Not yet final... I'm still looking for a way to get this working and I am using a zoomed in imageview as a map...
#Override
protected void onDraw(Canvas canvas) {
if (layout) {
if (drawable != null && !isRecycled()) {
canvas.save();
float adjustedScale = scale * scaleAdjust;
canvas.translate(x, y);
if (rotation != 0.0f) {
canvas.rotate(rotation);
}
if (adjustedScale != 1.0f) {
canvas.scale(adjustedScale, adjustedScale);
}
drawable.draw(canvas);
canvas.restore();
}
if (drawLock.availablePermits() <= 0) {
drawLock.release();
}
}
// ---add the marker---
Bitmap marker = BitmapFactory.decodeResource(getResources(),
R.drawable.search_marker_icon);
canvas.drawBitmap(marker, 40, 40, null);
Paint mPaint = new Paint();
mPaint.setColor(Color.RED);
canvas.drawCircle(60, 60, 5, mPaint);
super.onDraw(canvas);
}
Thanks.... I'm new to android :) hope you can help me....

This is a nice library for displaying images, which supports zooming/panning and adding pins over the image
https://github.com/davemorrissey/subsampling-scale-image-view

drawable.draw(canvas);
// ---add the marker---
Bitmap marker = BitmapFactory.decodeResource(getResources(),
R.drawable.search_marker_icon);
canvas.drawBitmap(marker, 40, 40, null);
Paint mPaint = new Paint();
mPaint.setColor(Color.RED);
canvas.drawCircle(60, 60, 5, mPaint);
canvas.restore();
}
if (drawLock.availablePermits() <= 0) {
drawLock.release();
}
}
super.onDraw(canvas);
}
You need to do this before canvas.restore..... :D got this solution last year...... thnx for the help guys.... my app is almost done :)

An implementation of an HTML map like element in an Android View:
Supports images as drawable or bitmap in layout
Allows for a list of area tags in xml
Enables use of cut and paste HTML area tags to a resource xml (ie, the ability to take an HTML map - and image and use it with minimal editing)
Supports panning if the image is larger than the device screen
Supports pinch-zoom
Supports callbacks when an area is tapped.
Supports showing annotations as bubble text and provide callback if the bubble is tapped
try this link you will find your solution https://github.com/catchthecows/AndroidImageMap

Related

How can I fingerpaint with touch over an image loaded by picasso

I am creating an app that pulls images from urls and puts them into a recyclerview. The user can then access those images and view it fullscreen. This is achieved with Picasso. I would now like the ability to fingerpaint over the image loaded with Picasso with an onTouchEvent or something but not sure how to do it.
This class sets the image to a map_edit_gallery.xml loaded with Picasso:
public class EditMapImage extends AppCompatActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_edit_gallery);
checkIntent();
//Find savebutton
ImageButton saveMapButton = findViewById(R.id.saveEditImagebutton);
saveMapButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_SHORT).show();
}
});
}
//This will check to see if the intent extras exist and if they do get the extra
private void checkIntent(){
if(getIntent().hasExtra("image_url") && getIntent().hasExtra("name_url")){
String imageUrl = getIntent().getStringExtra("image_url");
String nameUrl = getIntent().getStringExtra("name_url");
setMapImage(imageUrl, nameUrl);
}
}
private void setMapImage(String imageUrl, String nameUrl){
//Set the Text view
TextView name = findViewById(R.id.mapNameEditor);
name.setText(nameUrl);
//Set the Image
ImageView imageView = findViewById(R.id.mapEditScreen);
Picasso.get().load(imageUrl).into(imageView);
Picasso picasso = Picasso.get();
DrawToImage myTransformation = new DrawToImage();
picasso.load(imageUrl).transform(myTransformation).into(imageView);
}
}
EDIT:
This class has allowed me to draw over the loaded image using canvas but cannot figure out how to use touch to draw:
public class DrawToImage implements Transformation {
#Override
public String key() {
// TODO Auto-generated method stub
return "drawline";
}
public Bitmap transform(Bitmap bitmap) {
// TODO Auto-generated method stub
synchronized (DrawToImage.class) {
if(bitmap == null) {
return null;
}
Bitmap resultBitmap = bitmap.copy(bitmap.getConfig(), true);
Canvas canvas = new Canvas(resultBitmap);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(10);
canvas.drawLine(0, resultBitmap.getHeight()/2, resultBitmap.getWidth(), resultBitmap.getHeight()/2, paint);
bitmap.recycle();
return resultBitmap;
}
}
}
Try using the image selected by the user to set it in a canvas object and draw on the canvas object itself, as opposed to the image. There are plenty of tutorials out there to help you with how to draw on a canvas.
This process isn't connected with the Picasso Image Library in any way so I would recommend first getting the image through Picasso, then sending the image into your custom canvas implementation, then returning a bitmap/drawable which you could set into Picasso after editing.
There's also plenty of tutorials on how to export an image from the canvas to get your edited image when you need it.
I hope this helped, Panos.

How to blur background images in Android

What is the best way to blur background images like the image below? I saw some code and libraries but their are a couple of years old or like BlurBehind library, but it doesn't give the same effect.
The easiest way to do that is use a library. Take a look at this one: https://github.com/wasabeef/Blurry
With the library you only need to do this:
Blurry.with(context)
.radius(10)
.sampling(8)
.color(Color.argb(66, 255, 255, 0))
.async()
.onto(rootView);
This is an easy way to blur Images Efficiently with Android's RenderScript that I found on this article
Create a Class called BlurBuilder
public class BlurBuilder {
private static final float BITMAP_SCALE = 0.4f;
private static final float BLUR_RADIUS = 7.5f;
public static Bitmap blur(Context context, Bitmap image) {
int width = Math.round(image.getWidth() * BITMAP_SCALE);
int height = Math.round(image.getHeight() * BITMAP_SCALE);
Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
RenderScript rs = RenderScript.create(context);
ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
theIntrinsic.setRadius(BLUR_RADIUS);
theIntrinsic.setInput(tmpIn);
theIntrinsic.forEach(tmpOut);
tmpOut.copyTo(outputBitmap);
return outputBitmap;
}
}
Copy any image to your drawable folder
Use BlurBuilder in your activity like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
mContainerView = (LinearLayout) findViewById(R.id.container);
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);
Bitmap blurredBitmap = BlurBuilder.blur( this, originalBitmap );
mContainerView.setBackground(new BitmapDrawable(getResources(), blurredBitmap));
Renderscript is included into support v8 enabling this answer down to api 8. To enable it using gradle include these lines into your gradle file (from this answer)
defaultConfig {
...
renderscriptTargetApi *your target api*
renderscriptSupportModeEnabled true
}
Result
You can use:
Glide.with(getContext()).load(R.mipmap.bg)
.apply(bitmapTransform(new BlurTransformation(22)))
.into((ImageView) view.findViewById(R.id.imBg));
This requires the following addition to your build.gradle file:
implementation 'jp.wasabeef:glide-transformations:4.0.0'
The simplest way to achieve this is given below,
I)
Glide.with(context.getApplicationContext())
.load(Your Path)
.override(15, 15) // (change according to your wish)
.error(R.drawable.placeholder)
.into(image.score);
else you can follow the code below..
II)
1.Create a class.(Code is given below)
public class BlurTransformation extends BitmapTransformation {
private RenderScript rs;
public BlurTransformation(Context context) {
super( context );
rs = RenderScript.create( context );
}
#Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Bitmap blurredBitmap = toTransform.copy( Bitmap.Config.ARGB_8888, true );
// Allocate memory for Renderscript to work with
Allocation input = Allocation.createFromBitmap(
rs,
blurredBitmap,
Allocation.MipmapControl.MIPMAP_FULL,
Allocation.USAGE_SHARED
);
Allocation output = Allocation.createTyped(rs, input.getType());
// Load up an instance of the specific script that we want to use.
ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setInput(input);
// Set the blur radius
script.setRadius(10);
// Start the ScriptIntrinisicBlur
script.forEach(output);
// Copy the output to the blurred bitmap
output.copyTo(blurredBitmap);
toTransform.recycle();
return blurredBitmap;
}
#Override
public String getId() {
return "blur";
}
}
2.Set image to ImageView using Glide.
eg:
Glide.with(this)
.load(expertViewDetailsModel.expert.image)
.asBitmap()
.transform(new BlurTransformation(this))
.into(ivBackground);
Android 12, Preview 1 comes with built-in blur feature. We need not depend on external library now. Here is the code
imageView.setRenderEffect(
RenderEffect.createBlurEffect(
20.0f, 20.0f, SHADER_TITLE_MODE
)
)
Works only on Android 12 as of now so is not a universal solution yet
To blur a image
1 Set your target SDK and compile SDK to Android S in build.gradle
2.Use Render Effect
3.set blur as follows
your_view.setRenderEffect(
RenderEffect.createBlurEffect(
30f, //radius X
30f, //Radius Y
Shader.TileMode.[X]// X=CLAMP,DECAL,MIRROR,REPEAT
)
4.The 4 types of blend mode are
CLAMP- Replicate the edge color if the shader draws outside of its original bounds
DECAL- Render the shader's image pixels only within its original bounds
MIRROR- Repeat the shader's image horizontally and vertically, alternating mirror images so that adjacent images always seam.
REPEAT - Repeat the shader's image horizontally and vertically.
This worked for me. Tested on Android 9 and 12. Use Glide library to shrink the bitmap.
// Glide
implementation 'com.github.bumptech.glide:glide:4.13.0'
kapt 'com.github.bumptech.glide:compiler:4.13.0'
Glide.with(context).asBitmap().load(favorite.coverImage).into(object : CustomTarget<Bitmap>(2, 2) {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
ivContentHolder.setImageDrawable(BitmapDrawable(itemBinding.root.context.resources, resource))
}
override fun onLoadCleared(placeholder: Drawable?) {
ivContentHolder.setImageDrawable(null)
}
CustomTarget(2, 2) is the trick. The lower the value the more the blur effect. Basically its used to shrink the image size. Then all you have to do is set the shrunk bitmap to your imageView. And most important is to set ScaleType of the imageView to CenterCrop.
<ImageView
android:id="#+id/iv_content_holder"
android:layout_width="match_parent"
android:layout_height="96dp"
android:scaleType="centerCrop"
android:src="#color/purple_700"
app:layout_constraintBottom_toBottomOf="parent" />
The result will look something like this. Blur Effect Demo
this might not be the most efficient solution but I had to use it since the wasabeef/Blurry library didn't work for me. this could be handy if you intend to have some getting-blurry animation:
1- you need to have 2 versions of the picture, normal one and the blurry one u make with photoshop or whatever
2- set the images fit on each other in your xml, then one of them could be seen and that's the upper one
3- set fadeout animation on the upper one:
final Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {upperone.setVisibility(View.GONE);}
#Override
public void onAnimationRepeat(Animation animation) {}
});
upperone.startAnimation(fadeOut);
you can use Glide for load and transform into blur image,
1) for only one view,
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50)) // 0-100
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view)
2) if you are using the adapter to load an image in the item, you should write your code in the if-else block, otherwise, it will make all your images blurry.
if(isBlure){
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50))
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view )
}else{
val requestOptions = RequestOptions()
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions).load(imageUrl).into(view)
}
Android 12 (Api level 31) has new Theme parameters to apply for windows to blur background:
<style name="BlurryTheme" parent="...">
<item name="android:windowBackgroundBlurRadius">30dp</item>
<item name="android:windowBlurBehindEnabled">true</item>
<item name="android:windowBlurBehindRadius">10dp</item>
</style>
And also new API for View to apply blur effect android.view.View#setRenderEffect:
imageView.setRenderEffect(
RenderEffect.createBlurEffect(
20.0f, 20.0f, Shader.TileMode.CLAMP
)
)
You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/onboardingimg1">
<View
android:id="#+id/opacityFilter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:layout_alignParentBottom="true"
android:alpha="0.7">
</View>
</RelativeLayout>
Try below code..
Put This Code in On Create..
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Url="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIur0ueOsmVmFVmAA-SxcCT7bTodZb3eCNbiShIiP9qWCWk3mDfw";
// Picasso.with(getContext()).load(Url).into(img_profile);
// Picasso.with(getContext()).load(Url).into(img_c_profile);
bitmap=getBitmapFromURL(Url);
Bitmap blurred = blurRenderScript(bitmap, 12);//second parametre is radius
img_profile.setImageBitmap(blurred);
Create Below Methods.. Just Copy Past..
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
#SuppressLint("NewApi")
private Bitmap blurRenderScript(Bitmap smallBitmap, int radius) {
try {
smallBitmap = RGB565toARGB888(smallBitmap);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bitmap = Bitmap.createBitmap(
smallBitmap.getWidth(), smallBitmap.getHeight(),
Bitmap.Config.ARGB_8888);
RenderScript renderScript = RenderScript.create(getActivity());
Allocation blurInput = Allocation.createFromBitmap(renderScript, smallBitmap);
Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);
ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
Element.U8_4(renderScript));
blur.setInput(blurInput);
blur.setRadius(radius); // radius must be 0 < r <= 25
blur.forEach(blurOutput);
blurOutput.copyTo(bitmap);
renderScript.destroy();
return bitmap;
}
private Bitmap RGB565toARGB888(Bitmap img) throws Exception {
int numPixels = img.getWidth() * img.getHeight();
int[] pixels = new int[numPixels];
//Get JPEG pixels. Each int is the color values for one pixel.
img.getPixels(pixels, 0, img.getWidth(), 0, 0, img.getWidth(), img.getHeight());
//Create a Bitmap of the appropriate format.
Bitmap result = Bitmap.createBitmap(img.getWidth(), img.getHeight(), Bitmap.Config.ARGB_8888);
//Set RGB pixels.
result.setPixels(pixels, 0, result.getWidth(), 0, 0, result.getWidth(), result.getHeight());
return result;
}
This might be a very late reply but I hope it helps someone.
You can use third party libs such as RenderScript/Blurry/etc.
If you do not want to use any third party libs, you can do the below using alpha(setting alpha to 0 means complete blur and 1 means same as existing).
Note(If you are using point 2) : While setting alpha to the background, it will blur the whole layout. To avoid this, create a new xml containing drawable and set alpha here to 0.5 (or value of your wish) and use this drawable name (name of file) as the background.
For example, use it as below (say file name is bgndblur.xml):
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shape="rectangle"
android:src="#drawable/registerscreenbackground"
android:alpha="0.5">
Use the below in your layout :
<....
android:background="#drawable/bgndblur">
Hope this helped.
You can quickly get to blur effect by doing the following.
// Add this to build.gradle app //
Compile ' com.github.jgabrielfreitas:BlurImageView:1.0.1 '
// Add to XML
<com.jgbrielfreitas.core.BlurImageView
android:id="#+id/iv_blur_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
//Add this to java
Import com.jgabrielfreitas.core.BlueImageView;
// Under public class *activity name * //
BlurImageView myBlurImage;
// Under Oncreate//
myBlurImage = (ImageView) findViewById(R.id.iv_blur_image)
MyBlurImage.setBlue(5)
I hope that helps someone

how to load image with Universal ImageLoader without displaying

I'm trying to do something like this:
Android Map api v2 Custom marker with ImageView
But I'm stuck on using image loader.
Trying:
Bitmap bmImg = imageLoader.loadImageSync(url);
LogCat gives me
04-13 14:11:44.953: E/ImageLoader(18542): android.os.NetworkOnMainThreadException
Here's is my code. I have an ArrayList camera with all information needed (titrle, position, url, etc).
public void drawPicsOnMap()
{
String title = null;
String place = null;
for (int i = 0; i<camera.size(); i++)
{
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(80, 80, conf);
Canvas canvas = new Canvas(bmp);
// paint defines the text color,
// stroke width, size
Paint color = new Paint();
color.setTextSize(35);
color.setColor(Color.BLACK);
Camera cam = camera.get(i);
LatLng coord = new LatLng(cam.lat, cam.lon);
title = Integer.toString(cam.id);
place = cam.place;
String url = cam.img;
Bitmap bmImg = imageLoader.loadImageSync(url);
//modify canvas
canvas.drawBitmap(bmImg, 0,0, color);
canvas.drawText(title, 30, 40, color);
Marker mark = map.addMarker(new MarkerOptions()
.position(coord)
.title(title)
.snippet(place)
.icon(BitmapDescriptorFactory
.fromBitmap(bmp)));
markers.put(mark.getId(), url);
}
}
Try this:
imageLoader.loadImage(url, new SimpleImageLoadingListener(){
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
//write your code here to use loadedImage
}
});
Here
onLoadingComplete will be called on UI thread which makes it thread safe
You can not do any networking on the main thread. See for description. UIL usually creates the thread and stuff for you when you call displayImage, but loadImageSync does not. Either create a thread and load it or use an AsynTask.

Android View Disappearing When Go Outside Of Parent

I have a LinearLayout and ImageView inside this LinearLayout.
There is a translation effect for ImageView.
// v = ImageView
ObjectAnimator animation2 = ObjectAnimator.ofFloat(v, "translationY", 200);
animation2.setDuration(3000);
animation2.setTarget(v);
animation2.start();
Animation working but it's disappearing when ImageView go outside of LinearLayout.
How can i fix it without modify LinearLayout's height.
Find the ViewGroup that the ImageView belongs to and apply ViewGroup.setClipChildren(false).
By default, the drawing of the children is limited to the bounds of the parent ViewGroup.
Two attributes exist that may cause this to happen: clipChildren and clipToPadding. You'll need to set clipChildren to false for each parent ViewGroup whose bounds the object will animate out of. You also need to set clipToPadding to the immediate parent (and maybe more, but I haven't seen a case for it yet).
You can set both attributes in the XML
android:clipChildren="false"
android:clipToPadding="false"
or in code
viewGroup.setClipChildren(false);
viewGroup.setClipToPadding(false);
My implementation. It can probably help somebody:
Java version:
public static void setAllParentsClip(View v, boolean enabled) {
while (v.getParent() != null && v.getParent() instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) v.getParent();
viewGroup.setClipChildren(enabled);
viewGroup.setClipToPadding(enabled);
v = viewGroup;
}
}
call
setAllParentsClip(yourView, false); to disable the clipping in all the parents.
Edited:
Kotlin's version as an extension function:
fun View.setAllParentsClip(enabled: Boolean) {
var parent = parent
while (parent is ViewGroup) {
parent.clipChildren = enabled
parent.clipToPadding = enabled
parent = parent.parent
}
}
Call: yourView.setAllParentsClip(false)
In my case clipChildren did nothing but clipToPadding="false" fixed the problem. Go figure.
Get the view height, then add a percentage of the height to where it will slide to
public void SlideUp(View view){
float height = view.getHeight();
TranslateAnimation animate = new TranslateAnimation(0,0,0,0);
animate.setDuration(500);
animate.setFillAfter(true);
view.animate().translationY((float)(0-0.62*height)).start();
view.startAnimation(animate);
}
try to update camera position as in my case below:
ValueAnimator lockAnimator = ValueAnimator.ofFloat(1, 0); // value from 0 to 1
lockAnimator.setDuration(500);
lockAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator pAnimation) {
float value = (Float) (pAnimation.getAnimatedValue());
if (value < .6 && flipped) {
if (preview != null)
mCanvasImage.setImageBitmap(preview);
else
mCanvasImage.setImageBitmap(imageBitmap);
flipped = false;
}
if (value > .3 && value < .7) {
lyt_rlt_container.setCameraDistance(lyt_rlt_container.getCameraDistance() - 100);
} else {
lyt_rlt_container.setCameraDistance(lyt_rlt_container.getCameraDistance() + 100);
}
lyt_rlt_container.setRotationY(180 * value);
}
});
lockAnimator.start();

Not able to Edit a cropped photo in Android

I'm building an Android app where I have to edit a picture which has been picked from the phone gallery and cropped.
So in my layout, I have an ImageView where I am placing the cropped image
xml file
<ImageView
android:id="#+id/ivEditPhoto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight=".90"
android:src="#drawable/app_icon_big" />
Placing the cropped image in ImaveView
bitmapPic = (Bitmap) getIntent().getParcelableExtra(
"CroppedBitmapImage");
picView = (ImageView) findViewById(R.id.ivEditPhoto);
picView.setImageBitmap(bitmapPic);
The image is getting placed correctly. But the problem is when I try to edit it.
I have an edit button and on click of that I do the following which includes registering of On Touch Listener.
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Bitmap alteredPastedBitmap = Bitmap.createBitmap(bitmapPic.getWidth(),
bitmapPic.getHeight(), bitmapPic.getConfig());
pasteCanvas = new Canvas(alteredPastedBitmap);
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(5);
matrix = new Matrix();
pasteCanvas.drawBitmap(bitmapPic, matrix, paint);
picView.setOnTouchListener(this);
Then the following
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(this, v.getId(), Toast.LENGTH_SHORT).show();
if (v.getId() == R.id.ivEditPhoto) {
Toast.makeText(this, "onTouch", Toast.LENGTH_SHORT).show();
int action = event.getAction();
x = event.getX();
y = event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
sX = event.getX();
sY = event.getY();
break;
case MotionEvent.ACTION_UP:
if (skewedBitmap == null) {
int resID = 0;
if (imageId == 0)
resID = R.drawable.green_arrow;
else
resID = imageId;
bitmapToPaste = BitmapFactory.decodeResource(
getResources(), resID);
} else {
bitmapToPaste = skewedBitmap;
skewedBitmap = null;
}
pasteCanvas.drawBitmap(bitmapToPaste, sX- (bitmapToPaste.getWidth() / 2),sY- (bitmapToPaste.getHeight() / 2), null);
picView.invalidate();
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
}
return true;
}
The issue is:
the bitmapPic.getWidth() and bitmapPic.getHeight() is 160*160 and the onTouch event.getX(); and event.getY(); is beyond the co-ordinates (For example: 150.33 & 500.89) although the image seems to be occupying the whole screen and the touch is on the image. So onTouch doesn't place the bitmap and returns a false.
Could any of you please guide me on this?
I had the same issue in one of my applications. I need to see more of your code but this could be related to the onInterceptTouch() method you need to implement.
If that is not the case, then maybe you can look into this code for help on how to move, modify and rotate bitmaps:
http://adblogcat.com/custom-view-to-draw-rotate-erase-and-convert-images-to-black-and-white/
I wrote this tutorial btw and this is my website and I think is easier for you to follow that tutorial than just paste it here.

Categories

Resources