안드로이드:영상 보기에서 영상을 각도만큼 회전
저는 ImageView의 이미지를 각도만큼 회전시키기 위해 다음 코드를 사용하고 있습니다.좀 더 간단하고 덜 복잡한 방법이 있습니까?
ImageView iv = (ImageView)findViewById(imageviewid);
TextView tv = (TextView)findViewById(txtViewsid);
Matrix mat = new Matrix();
Bitmap bMap = BitmapFactory.decodeResource(getResources(),imageid);
mat.postRotate(Integer.parseInt(degree));===>angle to be rotated
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,bMap.getWidth(),bMap.getHeight(), mat, true);
iv.setImageBitmap(bMapRotate);
mImageView.setRotation(angle)API>=11
을 또ImageView:
:
기:
import android.graphics.Matrix;
import android.widget.ImageView;
( : ()imageView,angle,pivotX&pivotY이미 정의되어 있음)
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);
이 메서드는 매번 새 비트맵을 만들 필요가 없습니다.
하려면:
ImageView실행 시 on touch에서 touchlistener를 설정할 수 있습니다.ImageView& 터치 청취자 ACTION_MOVE 부분의 위 코드 섹션에서 마지막 두 줄(즉, 후 회전 행렬을 추가하여 imageView에 설정)을 추가하여 회전합니다.
API 11 이상을 지원하는 경우 다음 XML 특성을 사용할 수 있습니다.
android:rotation="90"
Android Studio xml 미리 보기에 올바르게 표시되지 않을 수 있지만 예상대로 작동합니다.
이를 위한 두 가지 방법이 있습니다.
1 사용하기Matrix법:
imageView = (ImageView) findViewById(R.id.imageView);
Bitmap myImg = BitmapFactory.decodeResource(getResources(), R.drawable.image);
Matrix matrix = new Matrix();
matrix.postRotate(30);
Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(), myImg.getHeight(),
matrix, true);
imageView.setImageBitmap(rotated);
RotateAnimationViewRotate을이 Rotate(회전)전)션 애니메이션우)으로합니다.fillAfter=true,duration=0,그리고.fromDegrees=toDgrees
<?xml version="1.0" encoding="utf-8"?>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="45"
android:toDegrees="45"
android:pivotX="50%"
android:pivotY="50%"
android:duration="0"
android:startOffset="0"
/>
애니메이션을 코드로 부풀립니다.
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotation);
myView.startAnimation(rotation);
너무 늦었다는 것은 알지만, 다른 사람들에게 도움이 될 수 있도록 저에게 도움이 되었습니다.
의 하여 ImageView 의를 의 절대 회전을 할 수 imageView.setRotation(angleInDegrees);방법.
절대적으로, 현재 회전을 추적할 필요 없이 이 함수를 반복적으로 호출할 수 있습니다.까를 15FsetRotation()를 호출한 드를 합니다.setRotation()h로30F입니다. , 은 45 30 입니다.
참고: 이 기능은 ImageView뿐만 아니라 View 개체의 모든 하위 클래스에서도 실제로 작동합니다.
코틀린이를 위해,
mImageView.rotation = 90f //angle in float
이렇게 하면 영상이 회전됩니다영상이 회전되지 않고 보기
또한, 비록 그것은 에 있는 방법입니다.View클래스(class)를 사용하면 거의 모든 뷰를 회전할 수 있습니다.
이 방법으로도 수행할 수 있습니다.
imageView.animate().rotation(180).start();
Android에서 이미지를 지연시켜 회전합니다.
imgSplash.animate().rotationBy(360f).setDuration(3000).setInterpolator(new LinearInterpolator()).start();
이것이 제가 구현한 Rotable ImageView입니다.attrs.xml과 RotableImageView.java를 프로젝트에 복사하고 레이아웃에 RotableImageView를 추가하면 사용이 매우 쉽습니다.예제:angle 파라미터를 사용하여 원하는 회전 각도를 설정합니다.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:example="http://schemas.android.com/apk/res/com.example"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.views.RotatableImageView
android:id="@+id/layout_example_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/ic_layout_arrow"
example:angle="180" />
</FrameLayout>
이미지를 표시하는 데 문제가 있는 경우 RotableImageView.onDraw() 메서드에서 코드를 변경하거나 대신 draw() 메서드를 사용합니다.
또한 ImageView를 세로 또는 가로로 180도 회전하려면scaleY아니면scaleX다로 합니다.-1f 다음은 코틀린의 예입니다.
imageView.scaleY = -1f
imageView.scaleX = -1f
1f데 value는 ImageView됩니다.
imageView.scaleY = 1f
imageView.scaleX = 1f
제가 해결책이 있습니다.사실 회전 후 발생하는 문제(직사각 이미지가 ImagueView와 맞지 않음)에 대한 해결책이지만, 본인의 문제도 다루고 있습니다.이 솔루션에는 좋든 나쁘든 애니메이션이 있습니다.
int h,w;
Boolean safe=true;
활동 초기화 시 imageView의 매개 변수를 가져올 수 없습니다. 이렇게 하려면 이 솔루션을 참조하거나 버튼 클릭 시 치수를 설정하십시오.
rotateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(imageView.getRotation()/90%2==0){
h=imageView.getHeight();
w=imageView.getWidth();
}
.
.//Insert the code Snippet below here
}
그리고 ImageView를 회전할 때 실행할 코드
if(safe)
imageView.animate().rotationBy(90).scaleX(imageView.getRotation()/90%2==0?(w*1.0f/h):1).scaleY(imageView.getRotation()/90%2==0?(w*1.0f/h):1).setDuration(2000).setInterpolator(new LinearInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
safe=false;
}
@Override
public void onAnimationEnd(Animator animation) {
safe=true;
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}).start();
}
});
이 솔루션은 위의 문제를 해결하기에 충분합니다.필요하지 않더라도(높이가 너비보다 작은 경우) 영상 보기가 축소됩니다.번거로우시다면 스케일 X/scale Y 안에 다른 3원 연산자를 추가할 수 있습니다.
내가 생각하는 최선의 방법 :)
int angle = 0;
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
angle = angle + 90;
imageView.setRotation(angle);
}
});
ImageView의 회전 속성을 간단히 사용할 수 있습니다.
아래는 Android 소스의 세부 정보와 함께 ImageView의 속성입니다.
<!-- rotation of the view, in degrees. -->
<attr name="rotation" format="float" />
안타깝게도, 없는 것 같아요. 그.Matrix클래스는 회전, 축소/성장, 스큐잉 등 모든 이미지 조작을 담당합니다.
http://developer.android.com/reference/android/graphics/Matrix.html
죄송합니다만, 대안을 생각할 수가 없네요.다른 사람이 할 수 있을지도 모르지만, 이미지를 조작해야 했던 시간들은 매트릭스를 사용했습니다.
행운을 빌어요!
이것을 커스텀 뷰로 해 보다.
public class DrawView extends View {
public DrawView(Context context,AttributeSet attributeSet){
super(context, attributeSet);
}
@Override
public void onDraw(Canvas canvas) {
/*Canvas c=new Canvas(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1) );
c.rotate(45);*/
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1), 0, 0, null);
canvas.rotate(45);
}
}
이미지에 회전 드로잉을 넣을 수 있는 좋은 솔루션 보기:
Drawable getRotateDrawable(final Bitmap b, final float angle) {
final BitmapDrawable drawable = new BitmapDrawable(getResources(), b) {
@Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, b.getWidth() / 2, b.getHeight() / 2);
super.draw(canvas);
canvas.restore();
}
};
return drawable;
}
용도:
Bitmap b=...
float angle=...
final Drawable rotatedDrawable = getRotateDrawable(b,angle);
root.setImageDrawable(rotatedDrawable);
다른 대안:
private Drawable getRotateDrawable(final Drawable d, final float angle) {
final Drawable[] arD = { d };
return new LayerDrawable(arD) {
@Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, d.getBounds().width() / 2, d.getBounds().height() / 2);
super.draw(canvas);
canvas.restore();
}
};
}
또한 비트맵을 회전하고 싶지만 OOM이 두렵다면 여기서 만든 NDK 솔루션을 사용할 수 있습니다.
보기를 시각적으로만 회전하려는 경우 다음을 사용할 수 있습니다.
iv.setRotation(float)
영상을 180도 회전하려면 다음 두 값을 영상 보기 태그에 넣습니다.-
android:scaleX="-1"
android:scaleY="-1"
설명:- scaleX = 1, scaleY = 1은 정상 상태를 나타내지만, scaleX/scaleY 속성에 -1을 넣으면 180도 회전합니다.
도 있고, 를 발견했습니다. 누군가가 유용하다고 생각할 수도 있습니다. 회전 og를 애니메이션으로 만들어야 하는 상황을 우연히 발견했습니다.ImageView어느 정도angle처음에ClickListener이벤트 그리고 2일에ClickListener이벤트, need torotate이미지를 원래 각도로 되돌립니다.이런 식으로 마법이 일어난 거지
fun rotateAnim(imageView: ImageView,angle : Float){
imageView.isEnabled = false
Log.i(TAG, "onCreate: ${imageView.rotation}")
val rotation = imageView.animate().rotationBy(angle)
rotation.interpolator = FastOutSlowInInterpolator()
rotation.startDelay = 200
rotation.setListener(object : Animator.AnimatorListener{
override fun onAnimationEnd(animation: Animator?) {
imageView.isEnabled = true
}
override fun onAnimationStart(animation: Animator?) {}
override fun onAnimationCancel(animation: Animator?) {}
override fun onAnimationRepeat(animation: Animator?) {}
})
rotation.start()
}
그리고 구현은 마치
holder.itemView.setOnClickListener {
val rotation = imageView.rotation
if(rotation == 180F){
rotateAnim(imageView,90F)
}else{
rotateAnim(imageView,-90F)
}
}
Kotlin 사용하기:
imageView.rotation = degrees.toFloat()
사용자 정의 이미지 보기(예:RotateableImageView extends ImageView....그리고 onDraw()를 재정의하여 캔버스/비트맵 중 하나를 회전한 후 캔버스로 다시 렌더링합니다.캔버스를 다시 복원하는 것을 잊지 마십시오.
그러나 이미지 보기의 단일 인스턴스만 회전하려면 솔루션이 충분해야 합니다.
매트릭스 및 애니메이션이 없는 경우:
{
img_view = (ImageView) findViewById(R.id.imageView);
rotate = new RotateAnimation(0 ,300);
rotate.setDuration(500);
img_view.startAnimation(rotate);
}
활동 결과에 이 내용만 적으면 됩니다.
Bitmap yourSelectedImage= BitmapFactory.decodeFile(filePath);
Matrix mat = new Matrix();
mat.postRotate((270)); //degree how much you rotate i rotate 270
Bitmap bMapRotate=Bitmap.createBitmap(yourSelectedImage, 0,0,yourSelectedImage.getWidth(),yourSelectedImage.getHeight(), mat, true);
image.setImageBitmap(bMapRotate);
Drawable d=new BitmapDrawable(yourSelectedImage);
image.setBackground(d);
이 코드를 100% 사용해 보십시오.
회전 버튼을 클릭하면 다음 코드를 작성됩니다.
@Override
public void onClick(View view) {
if(bitmap==null){
Toast.makeText(getApplicationContext(), "Image photo is not yet set", Toast.LENGTH_LONG).show();
}
else {
Matrix matrix = new Matrix();
ivImageProduct.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate(90,ivImageProduct.getDrawable().getBounds().width()/2,ivImageProduct.getDrawable().getBounds().height()/2);
Bitmap bmp=Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
bitmap=bmp;
ivImageProduct.setImageBitmap(bitmap);
}
}
이미지를 비트맵으로 변환한 다음 회전하는 대신 코드 아래와 같이 직접 이미지 보기를 회전합니다.
ImageView myImageView = (ImageView)findViewById(R.id.my_imageview);
AnimationSet animSet = new AnimationSet(true);
animSet.setInterpolator(new DecelerateInterpolator());
animSet.setFillAfter(true);
animSet.setFillEnabled(true);
final RotateAnimation animRotate = new RotateAnimation(0.0f, -90.0f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
animRotate.setDuration(1500);
animRotate.setFillAfter(true);
animSet.addAnimation(animRotate);
myImageView.startAnimation(animSet);
영상 보기를 연속적으로 회전하려면 다음 답변을 따릅니다.
int i=0;
회전 버튼을 클릭한 경우
imageView.setRotation(i+90);
i=i+90;
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);
사용방법은?
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textChanger;
ImageView imageView;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textChanger = findViewById(R.id.textChanger);
imageView=findViewById(R.id.imageView);
textChanger.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
roateImage(imageView);
}
});
}
private void roateImage(ImageView imageView) {
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);
}
}
언급URL : https://stackoverflow.com/questions/8981845/android-rotate-image-in-imageview-by-an-angle
'programing' 카테고리의 다른 글
| 가로 세로에서 소프트 키보드 입력에 대해 전체 화면 편집 보기를 비활성화하시겠습니까? (0) | 2023.10.14 |
|---|---|
| 최대 절전 모드 둘 다 복합 기본 키가 있는 경우 관련 없는 두 테이블에 가입 (0) | 2023.10.14 |
| git 저장소를 데이터베이스 백엔드로 사용 (0) | 2023.10.14 |
| Windows에서 COM(시리얼) 포트를 나열하시겠습니까? (0) | 2023.10.14 |
| 애니메이션 요소 변환 회전 (0) | 2023.10.14 |